1

Struct members can use the same name as a type, but it appears that global variables cannot. Does anyone know why? I am using MinGW-64, an implementation of GNU C.

typedef struct foo{

}foo;

foo foo;

int main()
{

}

Thanks!

1
  • Struct members have their own namespace. A global variable is in the same global namespace as the typedef. Jul 19, 2020 at 18:00

2 Answers 2

1

The issue here is fairly simple. You cannot redefine the meaning of a name in the same scope it is defined. To contrast, this would be valid

typedef struct foo{
  char c;
}foo;

int main()
{
    foo foo;
}

Following the declaration in the scope of main, the meaning of foo is altered. But when you do it in the same scope as the type alias, you are basically providing conflicting definitions.

Struct fields aren't in the scope of the type definition itself. So that's why those don't conflict either.

2
  • Member names were never part of the same name space as object and type names, to my memory, but they were all in one name space of structure and union member names, instead of separate name spaces for each structure or union. Jul 19, 2020 at 18:14
  • @EricPostpischil - Yeah, I figured I might be misremembering. Thanks Jul 19, 2020 at 18:16
0

When compiled with gcc, this error is produced:

test.c:5:5: error: ‘foo’ redeclared as different kind of symbol
 foo foo;

This is the issue. The statement foo foo; tries to re-declare the symbol foo as a variable when it has already been declared to refer to struct foo. You can fix your issue by changing the name of the variable to something else.

9
  • even with a typedef in the struct's declaration? Jul 19, 2020 at 17:55
  • but my point was that in the example the struct is declared with a typedef, so it surprises me that you can't then do foo foo; Jul 19, 2020 at 17:56
  • Other than not actually answering the question, this misses that in the OP's code they used a typedef along with the struct definition. Thus allowing the use of both struct foo and foo. Jul 19, 2020 at 17:57
  • 1
    Do you mean you can't declare a variable of the same name as its type? You can, when scoping permits. Also, foo is not a keyword. Jul 19, 2020 at 18:04
  • 2
    I suggest you tidy up your answer to say what you mean with precision. This is ultimately what many people will judge an answer upon. Jul 19, 2020 at 18:18

Your Answer

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

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