c++ - C/C++ union 和未定义行为

标签 c++ c language-lawyer undefined-behavior unions

以下是未定义的行为吗?

 union {
   int foo;
   float bar;
 } baz;

 baz.foo = 3.14 * baz.bar;

我记得在两个序列点之间写入和读取同一底层内存是 UB,但我不确定。

最佳答案

I remember that writing and reading from the same underlying memory between two sequence points is UB, but I am not certain.

读取和写入同一表达式中的同一内存位置不会调用未定义的行为,除非该位置在两个序列点之间被修改多次,或者副作用相对于使用值计算的值是无序的相同的位置。

C11:6.5 表达式:

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. [...]

表达式

 baz.foo = 3.14 * baz.bar;  

如果 bar 在之前初始化,则具有明确定义的行为。原因是 baz.foo 的副作用是相对于对象 baz.foobaz.bar 的值计算排序的。

C11: 6.5.16/3 赋值运算符:

[...] The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

关于c++ - C/C++ union 和未定义行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33291146/

相关文章:

c++ - 用 boost::assign::list_of 填充 std::deque<std::vector<std::string>>

c++ - 通过 constness 从结构传递到它的指针和引用成员

c - GDB 说 "no symbol table,"但 nm 显示文件有调试符号

c++ - 移动成员函数生成

c++ - typedef 的使用无效?

c++ - 设置视频捕获属性不再适用于 OpenCV 2.2?

c - char 的 Scanf 输入工作一次然后是空白

c - 使用 pthread 库时出现段错误

c++ - 不同翻译单元中类的多重定义

c++ - "a subsequent condition of that statement"的标准是什么意思?