A question about union in C – store as one type and read as another – is it implementation defined?

This is undefined behaviour. u.i and u.ch are located at the same memory address. So, the result of writing into one and reading from the other depends on the compiler, platform, architecture, and sometimes even compiler’s optimization level. Therefore the output for u.i may not always be 515. Example For example gcc on my machine … Read more

Is it allowed to use unions for type punning, and if not, why?

To re-iterate, type-punning through unions is perfectly fine in C (but not in C++). In contrast, using pointer casts to do so violates C99 strict aliasing and is problematic because different types may have different alignment requirements and you could raise a SIGBUS if you do it wrong. With unions, this is never a problem. … Read more

Unions as Base Class

Tony Park gave an answer which is pretty close to the truth. The C++ committee basically didn’t think it was worth the effort to make unions a strong part of C++, similarly to the treatment of arrays as legacy stuff we had to inherit from C but didn’t really want. Unions have problems: if we … Read more

sizeof a union in C/C++

A union always takes up as much space as the largest member. It doesn’t matter what is currently in use. union { short x; int y; long long z; } An instance of the above union will always take at least a long long for storage. Side note: As noted by Stefano, the actual space … Read more

Anonymous union within struct not in c99?

Anonymous unions are a GNU extension, not part of any standard version of the C language. You can use -std=gnu99 or something like that for c99+GNU extensions, but it’s best to write proper C and not rely on extensions which provide nothing but syntactic sugar… Edit: Anonymous unions were added in C11, so they are … Read more