How to assign and output values in a C language union?
In C language, you can use the assignment operator (=) to assign values to union variables. The members of a union can be accessed using the dot operator (.).
Here is an example demonstrating how to assign values and output a shared variable in the C language.
#include <stdio.h>
union MyUnion {
int num;
char ch;
};
int main() {
union MyUnion u;
// 给共用体变量赋值
u.num = 65;
// 输出共用体的成员
printf("num = %d\n", u.num);
printf("ch = %c\n", u.ch);
return 0;
}
Output result:
num = 65
ch = A
In this example, the union MyUnion has two members: num and ch. When we assign a value of 65 to num, the member ch in the union will also be assigned the corresponding ASCII character (in this case, the uppercase letter “A”). Because the members of the union share the same memory space, assigning a value to one member will affect the value of the other member.