Home > Mobile >  Why must a struct member always have an identifier?
Why must a struct member always have an identifier?

Time:11-07

Why must a struct member always have an Identifier? The answer of course is because that is how the language is defined, but I'd like to understand the reason behind it.

typedef union {
    int a;
    struct {
        int a; //Why is an identifier necessary here?
        int b;
    } s;
} u;

CodePudding user response:

There are grammar complications here. Consider int a, b, c;. That declares three objects. int a, b; declares two, and int a; declares one. So how many should int; declare? When a declaration with no declarator appears in other contexts, it does not declare any object. For example, struct foo { int x; }; defines the type struct foo, but it does not declare an object of that type.

We could make an exception for declarations in structures, and say that, if they have no declarators, then they declare one unnamed member. But then we are introducing another special case in to the grammar. Then struct foo { int x; };, which has no declarator, would declare a member object of type struct foo when it appears inside a structure definition, but it would not declare any object when it appears outside of a structure definition.

So this adds complications to the language. And it is not necessary; somebody who wants a member in a structure can always give it a name and can choose a name that will not interfere with other code.

CodePudding user response:

Actually, bit field members do not need a name, at least according to gcc -std=c99 -Wall -Wextra -pedantic, which gives no warning when compiling this code:

struct Foo
{
  char x;
  unsigned :8;
};

If you really don't want to have an identifier for a member that isn't a bit-field, you can name it something like _reserved0 to explicitly show that this is just reserved space that you don't want to access from your code.

I don't know the opinions of the people who wrote the C standard. Maybe they were thinking a struct member without a name was almost always a bug (i.e. the programmer forgot the name), and they wanted to help people catch those bugs, but they made a few exceptions to the rule.

CodePudding user response:

//Why is an identifier necessary here?

This a is distinct from the a outside the structure. The compiler needs to know which one you want to access

If you use distinct names you can use anonymous structure in your union

typedef union {
    int a;
    struct {
        int b;
        int c;
    };
} u;

u foo(int x, int y, int z)
{
   u un;
   u.a = x;
   u.b = y;
   u.c = z;
}
  • Related