C Accessing Union Members

#include <stdio.h>

union MyUnion {
    int int_value;
    float float_value;
    char char_value;
};

int main() {
    union MyUnion u;

    u.int_value = 65;

    printf("Integer value: %d\n", u.int_value);
    printf("Float value: %f\n", u.float_value);
    printf("Character value: %c\n", u.char_value);

    return 0;
}

Explanation:

  • #include <stdio.h>: Includes the standard input-output library to use functions like printf.

  • union MyUnion {...};: Defines a union named MyUnion that contains three members: int_value of type int, float_value of type float, and char_value of type char. In a union, all members share the same memory location.

  • int main() { ... }: The main function where the program execution begins.

  • union MyUnion u;: Declares a variable u of type MyUnion.

  • u.int_value = 65;: Assigns the value 65 to the int_value member of the union u.

  • printf("Integer value: %d\n", u.int_value);: Prints the value of u.int_value as an integer using the %d format specifier.

  • printf("Float value: %f\n", u.float_value);: Prints the value of u.float_value as a float using the %f format specifier. Since the union shares memory, accessing any member after assigning a value to one member may lead to unpredictable results due to the way memory is interpreted.

  • printf("Character value: %c\n", u.char_value);: Prints the value of u.char_value as a character using the %c format specifier. Similar to the previous explanation, accessing a member after assigning a value to a different member in a union may lead to unexpected results due to memory interpretation.

  • return 0;: Indicates successful termination of the program.