0

I have a struct that declared as follow:

struct a {
    struct b {
        int d;
    } c;
};

How to declare a variable of b outside a? In C++ I can use a::b x;. But, in C it required to specifies struct keyword before struct name.

2 Answers 2

1

C has a flat layout; when you declare a struct within another struct, the former is just being put into the global namespace.

So, in your example, it is just struct b.

Sign up to request clarification or add additional context in comments.

3 Comments

Where does the standard say that?
@david.pfx not sure, but 6.2.1 If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope
@keltar: Actually, no. I think it might be 6.2.3 Name spaces and note 32, which make it clear there is only one namespace for tags, but a separate namespace for members of each struct or union.
1

C does not have nested types. You can't write a::x b or anything that ressembles it. If you want to get rid of the struct keyword, that's another problem. Use typedefs. but it won't allow to nest types.

typedef struct b_t {
  int d;
} b;
typedef struct {
  b c;
} a;
b some_b;
a some_a;
int f() {
  some_b.d=42;
  some_a.c=some_b;
  return 0;

}

.

Comments

Your Answer

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