I peeped from my colleagues in the project about the following structure:

struct A { int i; union { char j; double k; }; } a; ... aj = 'a'; 

The project on With, is compiled under gcc.
I found a description of similar use of the union for pluses, but earlier for C such (using a union without a name with simplified access to its fields) I did not come across before.

Is this a valid C construct, or is this one of the features of gcc? If you switch to another compiler with it, there will be no problems?

  • As I recall, it is quite compatible with the standard design. MSVC understands it too. - VladD
  • @VladD, it can of course be compatible for the standard of new readadision, but in none of my reference books on C there is such a use, if you have any links, share pliz. - margosh

1 answer 1

It is quite compatible with the C standard, starting with C11, construction. MSVC, which rather poorly supports the C standard, is nevertheless well aware of it.

In the C99 standard, this construction was not, but gcc nevertheless supported it as an extension of the language.

Wikipedia :

The standard includes several changes to the C99 language and library specifications, such as:

  • Anonymous structures and unions are useful, eg, in struct T { int tag; union { float x; int n; }; }; struct T { int tag; union { float x; int n; }; }; .

Reference to standard , §6.7.2.1 / 13:

It is anonymous structure ; anonymous union . The structure of the unanimous body of anonymous government is considered. This applies recursively if you have anonymous.

  • Therefore, such code will work on newer versions of compilers with C11 support. Thank! - margosh
  • @margosh: Please! - VladD