union intBytes { int32 myInt; struct { char char1; char char2; char char3; char char4; }; char charArray[4]; }; intBytes dummy;
You can see that no name is assigned to wrap the char1 - char4 structure. This is called anonymous struct . Members of an anonymous structure are directly accessible within the area surrounded by the structure.
Without struct char1 - char4 will overlap inside the union, and everyone will refer to the first byte of myInt . An anonymous structure ensures that char1 - char will be executed sequentially.
C has anonymous structures and associations. C ++ (pre C ++ 11) DOES NOT allow anonymous structures; only anonymous associations are defined. However, most C ++ compilers (llvm, gcc) allow anonymous structure / associations.
Anonymous structures have been added in C ++ in C ++ 11.
This allows you to access dummy.char4 , while normally you will need to enter dummy.nameOfCharStruct.char4 . Since this is not a standard C ++ correspondence (I believe that it was changed in post C ++ 03 Standatd), you might be better off adding a structure name or using an array approach.
source share