C / C ++ Unions and Undefined Behavior

Is the following behavior undefined?

 union {
   int foo;
   float bar;
 } baz;

 baz.foo = 3.14 * baz.bar;

I remember that writing and reading from the same base memory between two points in the sequence is UB, but I'm not sure.

+4
source share
2 answers

I remember that writing and reading from the same base memory between two points in the sequence is UB, but I'm not sure.

Reading and writing to the same memory location in the same expression does not cause undefined behavior until and unless this location is changed more than once between two points in the sequence or a side effect affects the calculation of the value using the value in the same location.

C11: 6.5 Expressions:

> , undefined. [...]

 baz.foo = 3.14 * baz.bar;  

, bar . , baz.foo baz.foo baz.bar.

6.5.16 (p3):

[...] . .

+3

: ++.

, - baz.bar - UB [basic.life]/(6.1).

, bar (, ), ; foo , , , . ; . CWG # 1116. - , (= ).

, (.. ) - . [expr.ass]/1.

+4

Source: https://habr.com/ru/post/1612838/


All Articles