mwh
mwh

Reputation: 61

c - struct in struct - valid c? - valid c++? - scope?

I would like to define the following structure and typedef:

typedef struct Atype
{
  int A;
  struct
  {
    int VERBOS;
  }
  IO;
}
Atype;

In main I then can define variables as:

Atype In1,In2;
In1.A=3;
In1.IO.VERBOS=4;
In2.IO=In1.IO;

etc.

The code compiles and runs (c - gcc-clang) but I have to write for different environments. My questions:

1) Are these nested structs without name valid c?

2) valid c++?

3) what is the scope of IO?

Upvotes: 0

Views: 186

Answers (3)

JaredPar
JaredPar

Reputation: 754585

This is a valid struct in C / C++ and it's called an unnamed struct. Here is a page from GCC that contains references to it

http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html

The scope of IO is no different than any other field in the struct

Upvotes: 2

toasted_flakes
toasted_flakes

Reputation: 2509

To avoid confusion, why not just this?

struct IO {
    int VERBOS;
};

typedef struct Atype {
  int A;
  struct IO;
} Atype;

Upvotes: 0

buc
buc

Reputation: 6358

  1. Yes.
  2. Yes.
  3. The same scope as A.

Upvotes: 0

Related Questions