union intBytes {
int32 myInt;
struct {
char char1;
char char2;
char char3;
char char4;
};
char charArray[4];
};
intBytes dummy;
Above you see that the struct wrapping char1
-char4
is not assigned a name. This is called an anonymous struct
. The members of an annonymous struct are directly accessible inside the scope sourrounding the struct.
Without the struct char1
- char4
would overlap inside the union and all would refer to the first byte of myInt
. The annonymous struct ensures that char1 - char get layed out sequentially.
C has anonymous structs and unions. C++ (pre C++11) does NOT allow anonymous structs, only anonymous unions are defined. However, most C++ compilers (llvm, gcc) allow anonymous struct/unions.
Anonymous structs were added to C++ in C++11.
This allows you to access dummy.char4
while usually you would have to type dummy.nameOfCharStruct.char4
. Since this is not standard conformant c++ (I believe it was changed in a post C++03 Standatd), you might be better of adding the name of the struct or using the array approach.