It makes sense to define mathematical constants as double values but what happens when one requires float values instead of doubles? Does the compiler automatically interpret the doubles as floats at compile-time (so they are actually treated as they were const floats) or is this conversion made at runtime?
It makes sense to define mathematical constants as double values but what happens when
Share
If by “defining”, you mean using
#define, here’s what happens:Say you have:
Now if you have:
you don’t get any warning for
xbecause the compiler automatically makesCONST1afloat. Fory, you get a warning becauseCONST2doesn’t fit in afloat, but the compiler casts it tofloatanyway.If by “defining”, you mean using
constvariables, here’s what happens:Say you have
Now if you have:
there is no way for the compiler to know the values of
CONST1andCONST2(*) and therefore cannot interpret the values asfloatat compile them. You will be given two warnings about possible loss of data and the conversion will be done at runtime.(*) Actually there is a way. Since the values are
const, the optimizer may decide not to take a variable for them, but replace the values throughout the code. This could get complicated though, as you may pass the address to these variables around, so the optimizer may decide not to do that. That is, don’t count on it.Note that, this whole thing is true for any basic type conversions. If you have
then you think
CONST3isint, but if you put it in afloat, it would becomefloatat compile-time, or if you put it in achar, it would becomecharat compiler-time.