Unions to extract data

Won't the union in this question cause UB when used as this:

union Data
    unsigned int intValue;
    unsigned char argbBytes[4];
Data data;
data.intValue = 1235347;
unsigned char alpha = data.argbBytes[0]; //UB?

I'm thinking about 9.5/1 in the standard:

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.


in general you are right, writing a value of one type to a union then reading it out as a different type is undefined behaviour. on the other hand iirc the standard explicitly allows anything to castable as a char array. it's never been 100% clear to me which takes precedence, but all implementations I have ever used allow union casting to do what you want anyway.

I suppose that'd be undefined as what you've done is platform specific. alpha would end up as a different value depending on whether your platform is big-endian or little-endian.

But, the technique you show is pretty much equivalent to doing a reinterpret_cast.

I think the standard is pointing out that you can't store different values in both members (as they overlap in memory).

The real reason union's were invented were to allow people to fit more data in a smaller amount of memory. Traditionally, along with a union, you'd save some marker (perhaps a bit or two stored in a bitmask) outside of the union to remember which member of the union is active. Using this marker, you'd carefully code accesses to the union so you only read the active member.

It is not clear from the post as to what is the size of 'int' on the platform. Assuming 32-bit integer, and 8-bit character, i.e. sizeof(int) == 4.

It is also not clear what is the endian-ness of the machine. Let us assume small endian.

With that undertanding, 0x12D993 (decimal 1235347) would be stored as

0x93 0xd9 0x12 0x00 (increasing address)

When this memory is accessed through 'argbBytes', the value of argbBytes[0] really depends on the endian-ness of the machine. Therefore, it is not an Undefined Behavior but an Implementation Defined Behavior.

Need Your Help

Setting Singleton property value in Firebase Listener

java android firebase singleton firebase-realtime-database

I'm currently testing out Firebase along with a Singleton model I plan to use to access during the lifecycle of the whole app. I'm now stuck with something that seems really trivial but I can't fig...

Trying to create odd irregular shaped button

android android-layout android-gridlayout

I am trying to create a keypad using Android Grid Layout. I would like one button that spans columns and rows in a 'L' Shape, for the Enter key.