gpt4 book ai didi

c - C中 union 变量的操作

转载 作者:行者123 更新时间:2023-12-04 11:55:13 24 4
gpt4 key购买 nike

这里是一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com