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
Here is the Visual-C++ disassembly for:
int main() {
double x = 0;
//
double y = 0.0;
//
double z = x * y;
return 0;
}
int main() {
00007FF758A32230 push rbp
00007FF758A32232 push rdi
00007FF758A32233 sub rsp,128h
00007FF758A3223A mov rbp,rsp
00007FF758A3223D mov rdi,rsp
00007FF758A32240 mov ecx,4Ah
00007FF758A32245 mov eax,0CCCCCCCCh
00007FF758A3224A rep stos dword ptr [rdi]
double x = 0;
00007FF758A3224C xorps xmm0,xmm0
00007FF758A3224F movsd mmword ptr [x],xmm0
//
double y = 0.0;
00007FF758A32254 xorps xmm0,xmm0
00007FF758A32257 movsd mmword ptr [y],xmm0
//
double z = x * y;
00007FF758A3225C movsd xmm0,mmword ptr [x]
00007FF758A32261 mulsd xmm0,mmword ptr [y]
00007FF758A32266 movsd mmword ptr [z],xmm0
return 0;
00007FF758A3226B xor eax,eax
}
00007FF758A3226D lea rsp,[rbp+128h]
00007FF758A32274 pop rdi
00007FF758A32275 pop rbp
00007FF758A32276 ret
They produced the same assembly. Visual-C++ uses the method of XOR-ing the XMM register with it'self. Had you first loaded the integer 0 then moved it into the XMM register it would have used an extra instruction. Given our hypothesis on how the 0.0 may be loaded as a literal, as well as the extra useless instruction load loading an integer 0 then moving it into a floating-point register, neither is optimal so it seems as though it really doesn't matter because the compiler writer we must assume this optimization has been know for a long time because it is kind of obvious. If 100% portability is required, then it is more portable to write an inline function that manually uses the XOR technique.