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 likeprintf
.union MyUnion {...};
: Defines a union namedMyUnion
that contains three members:int_value
of typeint
,float_value
of typefloat
, andchar_value
of typechar
. 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 variableu
of typeMyUnion
.u.int_value = 65;
: Assigns the value65
to theint_value
member of the unionu
.printf("Integer value: %d\n", u.int_value);
: Prints the value ofu.int_value
as an integer using the%d
format specifier.printf("Float value: %f\n", u.float_value);
: Prints the value ofu.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 ofu.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.