Home >Backend Development >C++ >Are Anonymous Structs in C Standard Compliant?
Anonymous Structs: Standard or Not?
According to MSDN, anonymous structs are non-standard in C . However, this statement raises the question of whether this distinction is accurate.
Standard Unnamed Structs
The C standard (both C 03 and C 11) allows the creation of unnamed structs as follows:
struct { int hi; int bye; };
These unnamed structs can be instantiated as members of other structs:
struct Foo { struct { int hi; int bye; } bar; };
Anonymous Structs in Visual C and GCC
What is often referred to as "anonymous structs" in Visual C and GCC is slightly different. These structs also allow accessing members directly through the parent object:
struct Foo { struct { // No member name int hi; int bye; }; }; int main() { Foo f; f.hi = 3; // Access member without using nested struct }
Non-Standard Anonymous Structs
This functionality of accessing members directly through the parent object is not standard. It is a Microsoft extension supported in Visual C and also by GCC. Windows API headers utilize this "anonymous struct" feature. However, it can be disabled by defining NONAMELESSUNION before including Windows header files.
Difference from Anonymous Unions
Standard anonymous unions also provide access to members directly through the parent object. For example:
struct Foo { union { // No member name int hi; int bye; }; }; int main() { Foo f; f.hi = 3; // Access member without using nested union }
Conclusion
The term "unnamed struct" in the standard refers to the overall type, while the term "anonymous struct" used in Visual C and GCC refers to the ability to access members directly through the parent object. This latter functionality is non-standard, though it remains widely supported by popular compilers.
The above is the detailed content of Are Anonymous Structs in C Standard Compliant?. For more information, please follow other related articles on the PHP Chinese website!