返回信息流```c++
#include <iostream>
// 假设你的编译器存储int类型时用四个字节,并且是小端
union ST
{
bool a;
int b;
};
int main()
{
ST a;
a.b = 100;
std::cout << a.a << std::endl; // 这打印什么
return 0;
}
```
这是一条镜像帖。来源:北邮人论坛 / cpp / #102405同步于 2022/12/1
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【bool类型】一个小题目供娱乐
YiYeShu
2022/12/1镜像同步8 回复
订阅后,新回复会通过你的通知中心匿名送达。
8 条回复
说的对,不过这题的结果和大小端没联系,我去题目里标一下吧,假设是小端~
【 在 Telephone 的大作中提到: 】
: 做这种题有啥意义啊?大小端不同的处理器跑出来结果都不一样
按照暖神的结论,这个题应该属于某种UB,能请教一下,有哪些UB行为吗,感谢。。
【 在 nuanyangyang 的大作中提到: 】
: 不是“从什么都不发生到机器冒烟、猫猫怀孕都有可能发生”吗?
参考 https://en.cppreference.com/w/cpp/language/union
> It is undefined behavior to read from the member of the union that wasn't most recently written.
$ clang++ -fsanitize=undefined -ox x.cpp && ./x
x.cpp:12:20: runtime error: load of value 100, which is not a valid value for type 'bool'
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior x.cpp:12:20 in
0
【 在 YiYeShu 的大作中提到: 】
: [md]
: ```c++
: #include <iostream>
: ...................
C11的spec附录里有个列表。https://iso-9899.info/n1570.html#J.2
cppreference也有个页面列举了几种典型。https://en.cppreference.com/w/cpp/language/ub
【 在 YiYeShu 的大作中提到: 】
: 按照暖神的结论,这个题应该属于某种UB,能请教一下,有哪些UB行为吗,感谢。。
懂了,,
【 在 Vampire 的大作中提到: 】
: 参考 https://en.cppreference.com/w/cpp/language/union
: > It is undefined behavior to read from the member of the union that wasn't most recently written.
: $ clang++ -fsanitize=undefined -ox x.cpp && ./x
: ...................