c - C中 union 变量的操作

标签 c union

这里是一个 union ,包含两种类型的变量intchar。如果我为 int 变量赋值,那么 char 变量中会出现什么?

例如

union a {
  int x;
  char j;
  char k;
} ua;
int main(){
  ua.x = 0xabcd;
  printf("%x",ua.j);
}

这里将打印什么值以及如何打印?

最佳答案

根据 C11 标准:

6.2.6 Representations of types
6.2.6.1 General
...
5 Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

但是这里的左值表达式是 char 类型,所以这是定义良好的行为。

同样相关的是来自

的注释

6.5.2.3 Structure and union members:
...
95) If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type as described in 6.2.6 (a process sometimes called ‘‘type punning’’). This might be a trap representation

printf 语句实际打印的内容取决于系统的字节顺序,也就是说它是实现定义的。

关于c - C中 union 变量的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54883904/

相关文章:

c - 原子结构的目的

mysql - 不能在 INSERT MySQL 中使用 UNION?

sql - 如何在没有ORDER BY的情况下订购UNION中的条目?

sql - 我需要合并来自 SQL 选择查询的两个结果

c - 通过 CONTEXT.Ebx+8 指向 baseAddress 的指针

c - 使用 lwIP 的原始 TCP API 时的性能问题

c - QEMU 中的 CPU 定时器供应

c - C 中的按位运算 - AnyOddBit

mysql - 合并 3 个表的电子邮件字段 n 检查注册用户表中是否存在相同的邮件

mongodb - 如何在 mongoDB 中编写联合查询