I think a simple “const” would have also done the trick. Sometimes -O3 is clever enough to figure out that the value is never written, so it makes it an asm constant.
It is mostly about the fact that if the variable is not static, then it's non-local to the translation unit and can be modified from everywhere else. So its value needs to be loaded and a plain and slow division is applied.
Having it local or const makes the compiler able to inline it and do a simple bitwise and with a constant.
So yes, make your variables static const by default (if you really need global).
Comments
I think a simple “const” would have also done the trick. Sometimes -O3 is clever enough to figure out that the value is never written, so it makes it an asm constant.
It is mostly about the fact that if the variable is not static, then it's non-local to the translation unit and can be modified from everywhere else. So its value needs to be loaded and a plain and slow division is applied.
Having it local or const makes the compiler able to inline it and do a simple bitwise and with a constant.
So yes, make your variables static const by default (if you really need global).
const_cast and linkage make const weaker than static on a variable that doesn't change.