Question

I have two files:

fir.c

int x = 7;
int y = 5;
int main()
{
    p2();
    printf("%d\n", x);
    return 0;
}

and also:

sec.c

double x;
void p2()
{
    x = 6;
}

After linking and compiling these two files, I'm printing x and get 0 as output. Moreover, after printing y, I get 4018000 as output. I understand that x overwrites y, but why do I get these values​​? What exactly does this mean?

Was it helpful?

Solution

First of all I'm pretty sure you using "%x" and not "%d in your printf. Second, I'm pretty sure it is 40180000 not 4018000 (an extra zero).

Assuming this is true, here's where you are getting this value:

In the first program, x and y are stored in the right next to each other in memory as ints (4 bytes). The second program links to the first program's "x" and treats it as a double (8 bytes), does not allocate new memory for the second program.

Now for the binary representation of "6" in IEEE double precision (link here)

0x01000000 00011000 00000000 00000000 00000000 00000000 00000000 00000000 is stored at "x"

HEX=0x4018000000000000

Since the first program sees only the int portion

0x01000000 00011000 00000000 00000000

=0x40180000

And since "%x" shows you the hex "40180000" is printed.

BTW: Reproduced your outcome just to make sure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top