Note that there are some explanatory texts on larger screens.

plurals
  1. POunion for uint32_t and uint8_t[4] undefined behavior?
    primarykey
    data
    text
    <p>In the comments of <a href="https://stackoverflow.com/a/8568531/1025391">this answer</a> it is said that it would be undefined behavior to split up an integer into their bytes using a union like follows. The code given at that place is similar though not identical to this, please give a note if have I changed undefined-behavior-relevant aspects of the code.</p> <pre><code>union addr { uint8_t addr8[4]; uint32_t addr32; }; </code></pre> <p>Up to now I thought this would be a fine approach to do things like <code>addr = {127, 0, 0, 1};</code> and get the corresponding <code>uint32_t</code> in return. (I acknowledge that this may yield different results depending on the endianness of my system. The question however remains.)</p> <p>Is this undefined behavior? If so, why? (I don't know what means <em>What's UB in C++ is to access inactive union members.</em>)</p> <hr> <p><strong>C99</strong></p> <ul> <li>C99 is apparantly pretty close to C++03 in this point.</li> </ul> <p><strong>C++03</strong></p> <ul> <li><em>In a union, at most one of the data members can be active at any time, that is, the value of at most one of the data members can be stored in a union at any time.</em> C++03, Section 9.5 (1), page 162</li> </ul> <p>However</p> <ul> <li><em>If a POD-union contains several POD-structs that share a common initial sequence [...] it is permitted to inspect the common initial sequence of any of POD-struct members</em> ibid.</li> <li><em>Two POD-struct [...] types are layout-compatible if they have the same number of nonstatic data members, and corresponding nonstatic data members (in order) have layout-compatible types</em> C++03, Section 9.2 (14), page 157</li> <li><em>If two types T1 and T2 are the same type, then T1 and T2 are layout-compatible types.</em> C++03, Section 3.9 (11), page 53</li> </ul> <p>Conclusion</p> <ul> <li>as <code>uint8_t[4]</code> and <code>uint32_t</code> are not the same type (I guess, a <a href="https://stackoverflow.com/a/99010/1025391">strict aliasing thing</a>) (plus both not being POD-structs/union) the above is indeed UB?</li> </ul> <p><strong>C++11</strong></p> <ul> <li><em>Note that aggregate type does not include union type because an object with union type can only contain one member at a time.</em> C++11, Footnote 46, page 42</li> </ul>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload