Union trick to typecast.

Ok you have all seen it and maybe even used it, but it is Undefined Bahaviour as the standard forbids it. What I am talking about is the following piece of code:



union foo{ int a; float b;};

foo f;

f.a = 10;

float f = f.b;

You may even have seen people like Danny Kalev from InformIT, who was also a previous standard committee member, using it. I do not care he is wrong and here is why:

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. [Note: one special guarantee is made in order to simplify the use of unions: If a POD-union contains several POD-structs that share a common initial sequence (9.2), and if an object of this POD-union type contains one of the POD-structs, it is permitted to inspect the common initial sequence of any of POD-struct members; see 9.2.

Please do not comment about this working in implementation X using compiler Y or on platform Z, it is none standard C++.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: