Tutorial by Examples

Unions are a specialized struct within which all members occupy overlapping memory. union U { int a; short b; float c; }; U u; //Address of a and b will be equal (void*)&u.a == (void*)&u.b; (void*)&u.a == (void*)&u.c; //Assigning to any union member changes ...
Unions are useful for minimizing memory usage for exclusive data, such as when implementing mixed data types. struct AnyType { enum { IS_INT, IS_FLOAT } type; union Data { int as_int; float as_float; } value; AnyType(int i) : type...
union U { int a; short b; float c; }; U u; u.a = 10; if (u.b == 10) { // this is undefined behavior since 'a' was the last member to be // written to. A lot of compilers will allow this and might issue a // warning, but the result will be "as expected"; thi...

Page 1 of 1