#include <stdio.h>
union p
{
int x;
char y;
}
k = {.y = 97};
int main()
{
printf("%d\n", k.y);
return 0;
}
OUTPUT: 97
我遇到了这个问题。正如我们所知,我们只能初始化 Union 的第一个成员。但是在这里,在初始化的时候,y
变量是通过一些给定的方法初始化的!
谁能给我解释一下 k={ .Y=97} 是如何违反 Dennis Ritchie 的书中所述的规则“Union can only be initialized with a value of the type of its first member "并改为初始化第二个变量?
最佳答案
K&R 是一本好书,但它很旧。在 C99 中你可以这样做。
Using a designated initializer in the same example, the following initializes the second union member age :
union {
char birthday[9];
int age;
float weight;
} people = { .age = 14 };
关于c - 如何解释这个 C union 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17135898/