0

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?

3 Answers 3

2

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

0
  1. Yes.
  2. Yes.
  3. The same scope as A.
1
  • Indeed this perfectly answered my question. I coded it with the intend to have valid C/C++ code and have IO in the same scope as A. However when trying to find the construct I made with the use of Google I got confused and was affright I used some buggy feature of my compiler.
    – mwh
    Jan 4, 2014 at 17:32
0

To avoid confusion, why not just this?

struct IO {
    int VERBOS;
};

typedef struct Atype {
  int A;
  struct IO;
} Atype;
2
  • Because this would put IO into the same scope as Atype, whereas the "struct in struct" solution (see below) places it only in the scope of the struct (same as A).
    – mwh
    Jan 4, 2014 at 15:16
  • @mwh Yes I know the difference of scope, but I feel it makes it easier to understand what's going on Jan 4, 2014 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.