Search code examples
cunions

C Unions output unclear


I got some troubles understanding unions and how they work.

#include <stdio.h>

union date {
    int year;
    char month;
    char day;
};

int main() {
    union date birth;
    birth.year = 1984;
    birth.month = 7;
    birth.day = 28;
    printf("%d, %d, %d\n", birth.year, birth.month, birth.day);
    return 0;
}

so since it's an union it will give me 4 bytes, because int is the highest type given in this union. that's all I got from reading and I dont know why the output is

1820, 28, 28

Solution

  • Unions in C use same memory allocation for variables defined in union. So, the total allocation is equal to size of the variable that need largest memory area.

    In your case, int (4 bytes), char, char (1 byte). Total memory allocation for whole union object is 4 bytes.

    4bytes = _ _ , _ _, _ _ , _ _ (memory location representation)

    assignment to year 1984 = 0x000007c0 (memory after first assignment)

    assignment to month will use same location = 0x00000707 (only 1 byte is changed)

    assignment to day 28 (0x1c) = 0x0000071c (final memory state)

    Now get day (1byte) = 0x1c (28)

    get month (1byte) = 0x1c (28)

    get year (4byte) =0x0000071c (1820)

    This is the whole story.