Search code examples
cfloating-pointcompile-time-constant

Compile time constants as floats


After converting a file with doubles to floats the compiler (MSCV2005) warns about conversions from double to float for in code constants like

...
float r;

r = (q1 + q2) * 0.5;
...

Even q1, q2 are both floats 0.5 seems to be treated as double.

How to adapt this behavious, so that all in-code constants are treated as floats?


Solution

  • Use an f suffix to indicate that the constant is to have type float:

    float q1 = ...;
    float q2 = ...;
    float r = (q1 + q2) * 0.5f;
    

    The standard (§6.4.4.2 Floating constants) says:

    An unsuffixed floating constant has type double. If suffixed by the letter f or F, it has type float. If suffixed by the letter l or L, it has type long double.

    The constant in your question has no suffix and so has type double.