Is there a difference between 0 and 0.0 in C++? Which should you use for initializing a double?
Thanks
Is there a difference between 0 and 0.0 in C++? Which should you use for initializing a double?
Thanks
A literal 0 is considered to be an int literal; literal 0.0 is a double literal. When assigning to a double, either will work (since the int can be cast in a widening conversion); however, casting 0.0 to an int is a narrowing conversion, and must be done explicitly; i.e. (int)0.0.
One appears to be an integer literal, the other a floating point literal. It really doesn't matter to the compiler whether you initialize floats or doubles with integer literals. In any event the literal will be compiled into some internal representation.
I would tend to suggest 0.0 in order to make your intention (to other programmers) explicitly clear.
I try to keep my constants type-consistent. 0 for ints. 0.0f or 0.f for float, and 0.0 for double.
To me, the most important reason to do this is so the compiler and the programmer see the same thing.
If I do this...
float t=0.5f;
float r;
r= 1 * t;
...should r be assigned 0 or .5? There's no hesitation if I do this instead...
float t=0.5f;
float r;
r= 1.0f * t;