Make C floating point literals float (rather than double)
-fsingle-precision-constant
flag can be used. It causes floating-point constants to be loaded in single precision even when this is not exact.
Note- This will also use single precision constants in operations on double precision variables.
Use warnings instead: -Wdouble-promotion
warns about implicit float to double promotion, as in your example. -Wfloat-conversion
will warn about cases where you may still be assigning doubles to floats.
This is a better solution than simply forcing double values to the nearest float value. Your floating-point code is still compliant, and you won't get any nasty surprises if a double value holds a positive value, say, less than FLT_DENORM_MIN
(assuming IEEE-754) or greater than FLT_MAX
.
You can cast the defined constants to (float)
wherever they are used, the optimizer should do its job. This is a portable solution.
#define LIMIT 2.5
if (x < (float)LIMIT) ...