Search code examples
c++cmemorymemory-managementunions

Understanding the memory content of a union


Suppose I define a union like this:

#include <stdio.h>

int main() {
    union u {
        int i;
        float f;
    };
    union u tst;
    tst.f = 23.45;

    printf("%d\n", tst.i);

    return 0;
}

Can somebody tell me what the memory where tst is stored will look like?

I am trying to understand the output 1102813594 that this program produces.


Solution

  • It depends on the implementation (compiler, OS, etc.) but you can use the debugger to actually see the memory contents if you want.

    For example, in my MSVC 2008:

    0x00415748  9a 99 bb 41
    

    is the memory contents. Read from LSB on the left side (Intel, little-endian machine), this is 0x41bb999a or indeed 1102813594.

    Generally, however, the integer and float are stored in the same bytes. Depending on how you access the union, you get the integer or floating point interpretation of those bytes. The size of the memory space, again, depends on the implementation, although it's usually the largest of its constituents aligned to some fixed boundary.

    Why is the value such as it is in your (or mine) case? You should read about floating-point number representation for that (look up ieee 754)