4

I need to verify that I can use unions a certain way.

For C99, this answer is adequate: Union element alignment

C99 - section 6.7.2.1 Structure and union specifiers (paragraph 14):

A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa.

Can someone please help me find the equivalent guarantee for C++?

More generally, is there a good source for finding section/paragraph citations for C++ standards which are equivalent to a known feature in C?

Thanks a lot.

Community
  • 1
  • 1
spraff
  • 32,570
  • 22
  • 121
  • 229

2 Answers2

6

In C++ (14882:2003), this is split between two paragraphs:

9.5[class.union]/1

Each data member is allocated as if it were the sole member of a struct.

9.2[class.mem]/17

A pointer to a POD-struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

I haven't heard of a cross-reference between C and C++ like that, it may be non-trivial, as this example shows.

Cubbi
  • 46,567
  • 13
  • 103
  • 169
  • Good citation. More generally, C++ was based on C specifically so it could be interoperable not just as the source level but at the binary data-handling level too. We can *expect* C++ union/struct padding/alignment/layout to match the equivalent C compiler (or C-only mode of the compiler). It's not worth researching every little aspect, especially as there are meaningful lists of the differences between C and C++ that really do bite during porting/interoperation. – Tony Delroy Mar 09 '11 at 13:35
0

FYI, if you want to check the C++ standard, unfortunately it is not available for free. You must pay a fee to get a copy of the standard. However, the final draft (the one before the approval) is available online: for C++99 http://www.kuzbass.ru:8086/docs/isocpp/, for C++0x http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3092.pdf.

Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • 2
    N3092 is a year old already (March 26, 2010), try N3242 (February 28, 2011) http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf – Cubbi Mar 09 '11 at 14:32