Home >Backend Development >C++ >Are Anonymous Structures in C Standard Compliant?
Are "Anonymous Structures" Standard in C ? A Detailed Analysis
Introduction
The concept of "anonymous structures" in C has raised questions about their standardization and precise nature. This article aims to clarify these issues by examining relevant documentation and exploring the subtle distinctions between different types of anonymous structures.
Are Anonymous Structures Non-Standard?
According to Microsoft's MSDN documentation, anonymous structures (structures defined without a name) are considered non-standard in C . However, the ISO C standards do not explicitly address this aspect.
Understanding Anonymous Structures
Unnamed Structs:
The C standard allows for the declaration of unnamed structs (structs without a name), which can be instantiated and used as regular named structs.
Anonymous Structs:
Anonymous structs refer to a specific feature in some C compilers (e.g., GCC and Visual C ) that allows access to members of an unnamed struct directly from the containing object.
The Distinction
The key distinction lies in the accessibility of members. In the case of unnamed structs, members are accessible through the standard dot operator (e.g., foo.bar), while anonymous structs allow directly accessing members without specifying the struct name (e.g., foo.hi).
Standard vs. Non-Standard
The standard defines the functionality of unnamed structs, but not specifically the "anonymous" behavior of directly accessing members. Therefore, the latter is considered a non-standard feature supported by certain compilers.
Example Usage
Standard Unnamed Struct:
struct Foo { struct { int hi; int bye; } bar; };
Non-Standard Anonymous Struct:
struct Foo { struct { int hi; int bye; }; // <--- no member name! };
In the second example, members can be accessed directly:
f.hi = 3; // Non-standard, compiler-dependent feature
Conclusion
Anonymous structures, as defined by their ability to directly access members from the containing object, are a non-standard feature supported by certain C compilers. Standard C provides the functionality of unnamed structs, but the direct accessibility of members is not specified and is not guaranteed to be supported.
The above is the detailed content of Are Anonymous Structures in C Standard Compliant?. For more information, please follow other related articles on the PHP Chinese website!