I have an hpp file with following code:
const float PixelsPerMeter = ConfigManager->Get<float>("koef", 100.0f);
inline const float Meters2Pixels(float meters) { return meters * PixelsPerMeter; }
inline const float Pixels2Meters(float pixels) { return pixels / PixelsPerMeter; }
const float ScreenArea = Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY);
It worked before, but now ScreenArea = inf somehow. I use it from static function. I put a breakpoint in that function and print out the value of PixelsPerMeter(100.0), ScreenSizeX and ScreenSizeY. Everything is okay, but ScreenArea is calculated wrong.
When I write directly Pixels2Meters(ScreenSizeX) * Pixels2Meters(ScreenSizeY) instead of using ScreenArea constant everything works.
How it could be?
I think, the problem is with your global variable, to be precise with its initialization.
If by the time the variable has not been dynamically initialized when you call
Pixels2Meters(), the variablePixelsPerMeteris statically initialized to zero, so the functionPixels2Meters()returnsinfwhich very much impliesPixelsPerMeteris zero.But you put break points, the story could be slightly different; it is analogous to Heisenberg uncertainty principle, in the sense that when you want to see the value of
PixelsPerMeterby putting breakpoints, it shows you different value than the value when there is no breakpoints.Also note that since the variable is declared
const, withoutexternkeyword, the variable has internal linkage, which means you will have different copy of this variable in each translation unit, in case if it declared in a header file which you include in several source files. The variable’s behavior is as if it is declaredstatic.Another important point to be noted is that this variable is initialized twice: the first initialization is called static initialization which happens at compile-time, and second initialization is called dynamic initialization which happens at runtime. In case of static initialization, the variable is initialized to zero, and that is the value which is being used which is causing the problem. To know more about it, read this:
You should also read about this:
staticinitialization order fiasco