Reputation: 1193
Is there any difference between
double x;
x=0;
and
double x;
x=0.0;
might be a stupid question but i can't really find the answer anywhere
Upvotes: 2
Views: 1617
Reputation: 400009
In practice, there doesn't have to be any difference although there is an implicit conversion in the first case since 0
is an int
.
I tried it (on assembly.ynh.io). This C code:
#include <stdio.h>
int main(void)
{
double x, y;
x = 0;
y = 0.;
printf("x=%g and y=%g\n", x, y);
return 0;
}
generated the following assembly for the two assignments (to x
and y
):
0008 B8000000 00 movl $0, %eax
000d 488945F0 movq %rax, -16(%rbp)
0011 B8000000 00 movl $0, %eax
0016 488945F8 movq %rax, -8(%rbp)
In other words, the code is exactly the same. This was built by GCC, without optimization.
I guess this takes advantage of the fact that the bitpatterns are all zero in both cases.
Upvotes: 3
Reputation: 1287
I guess there won't be any difference to your code output if used exactly like that, but with x=0
the compiler has to perform implicit type conversion of the 0 from an int
(0) to a double
(0.0). Worst case, increases your compile time by a few nanoseconds maybe?
Upvotes: 2
Reputation: 106092
Yes. In x = 0
there is an implicit type promotion performed to convert 0
(which in int
) to double
0.0
.
Upvotes: 3