Reputation: 1703
I have a piece of code:
Under Windows MSVC 2012
#include <stdio.h>
#include <string.h>
namespace myname{
double var = 42;
}
extern "C" double _ZN6myname3varE = 10.0;
int main(){
printf("%d\n", _ZN6myname3varE);
return 0;
}
The output is 0
. But I think the output should be 10
. Could you help explain why?
Upvotes: 1
Views: 417
Reputation: 122383
printf("%d\n", _ZN6myname3varE);
%d
should be changed to %f
, which prints type double
But there's another problem: name mangling. When I tested the program in gcc, it shows an error:
Error: symbol `_ZN6myname3varE' is already defined
The problem is the name _ZN6myname3varE
is a reserved identifier in C++ because it begins with underscore and an uppercase letter.
Upvotes: 0
Reputation: 1922
Answer for "But I want to know why 0 is output? How this happen?".
double
is 64-bit and int
is 32-bit
. When double
is truncated to int
(because of using %d
), only first 4
bytes stored in the memory location of double
is taken into the int
value.
Here, value of double _ZN6myname3varE
is 10.0
, which is 0x4024000000000000
in hex and stored as 00000000 00002440
in memory (little endian). So, when truncated to int
, only 4 byte LSB is taken which is obviously zero
.
Upvotes: 2