tags:

views:

540

answers:

4

Is there a difference between 0 and 0.0 in C++? Which should you use for initializing a double?

Thanks

+10  A: 

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.

Rob
and 0.0f is a float value. :D
CrazyJugglerDrummer
@Rob, are you saying that a double cannot be implicitly converted to an int? Consider `int a = 0.0;`.
Johannes Schaub - litb
A double can most certainly be assigned to an int without an explicit cast. This part of the answer needs to be revised.
Brian Neal
Maybe Rob means "must" in the sense of "to avoid warnings on <insert compiler and flags here>"? In the case of a constant which clearly is representable in an int, that seems overkill. But in general, conversion from double to int is dangerous because it's undefined for large values, so I certainly agree with the generalisation that narrowing conversions *should* be explicit.
Steve Jessop
@onebyone Of course it may not be desired but it is allowed implicitly without a cast by the language.
Brian Neal
+5  A: 

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.

Jim Dennis
A: 

0 is an integer literal. 0.0 is a float.

deeb
0.0 is a double.
Brian Neal
+4  A: 

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;
Nosredna
0.f sounds like a hexadecimal floating-point value :)
Pavel Shved
Yeah, C is in trouble if it ever wants to support float point hex literals, isn't it. :-)
Nosredna