Home >Backend Development >C++ >Why Doesn't C Allow Anonymous Structs While Permitting Anonymous Unions?

Why Doesn't C Allow Anonymous Structs While Permitting Anonymous Unions?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 15:25:12694browse

Why Doesn't C   Allow Anonymous Structs While Permitting Anonymous Unions?

The Rationale Behind the Disallowance of Anonymous Structs in C

C compilers may permit the use of anonymous unions and structs as extensions to the standard. However, the standard itself only allows anonymous unions, not anonymous structs. What lies behind this discrepancy?

The reason stems from compatibility with C. C supports anonymous unions, but not anonymous structs. To achieve compatibility, C incorporates anonymous unions into its language. However, there is no requirement for compatibility with anonymous structs in C, so they are omitted from the standard.

Moreover, anonymous structs serve little purpose in C . The example provided, where a struct holds three floats accessible through both .v[i] and .x, .y, .z, is considered undefined behavior in C . It is discouraged to write to one member of a union (.v[1]) and read from another (.y).

C offers alternative solutions through user-defined types. For instance:

struct vector3 {
  float v[3];
  float &operator[](int i) { return v[i]; }
  float &x() { return v[0]; }
  float &y() { return v[1]; }
  float &z() { return v[2]; }
};

This code provides the desired functionality while adhering to C standards. It would be prudent to use defined structures for managing data rather than anonymous structs, even though they are possible in certain compiler extensions.

The above is the detailed content of Why Doesn't C Allow Anonymous Structs While Permitting Anonymous Unions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn