I am aware that casting ints to floats (and vice versa) is fairly expensive. However, does the compiler automatically do it at compile time for constants in your code? For e.g. is there any difference between
float y = 123;
float x = 1 / y;
and
float y = 123.f;
float x = 1.f / y;
I see some code that does the latter, but I’m not sure if it’s for optimization or safety issues (ie just making sure that the divide is floating point even if y happens to be an int).
I’m using gcc (since the answer might be compiler specific.)
Also, any pointers to a list of what the compiler can and cannot optimize in general would be appreciated. Thanks!
Yes, the compiler will do the conversion automatically. Your two blocks of code are identical.
It is not an optimization. Turning off optimization won’t make the compiler include the int-to-float conversion in the executable code, unless it’s a very poor-quality implementation.
It’s not for safety, either. The compiler never does anything “just in case” an operand happens to be of a different type. The compiler knows the types of everything in your code. If you change the type of a variable, everything that uses that variable gets recompiled anyway; the compiler doesn’t try to keep everything else untouched and just update the changed sections.