c - 如何解释这个 C union 输出

标签 c unions

#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/

相关文章:

c - 如何使用lfind

c - 函数my_find_node返回第一个节点出现的地址

c++ - union 成员的析构函数似乎被自动调用

c - 用 C 编写一个安全的标记 union

c - 为什么 union 适用于 C 语言的低级系统编程?

c - 如果声明了 union,循环将不会显示

c - 使用 UDP 发送字符

python - 使用 python 中的 c 库(未定义的引用)

c# - 如何将 C++ union 类型转换为 C# 代码?

c - 用于进程内线程通信的posix队列与自定义0复制队列