以下是未定义的行为吗?
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.foo
和 baz.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/