Hello!
I have two questions. I need help understanding what a namespace is in C; and the scope of enum constants is puzzling me.
#1 The C11 standard draft states,
Thus, there are separate name spaces for various categories of identifiers, as follows:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by following any32 of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
32) There is only one name space for tags even though three are possible.
What exactly is a namespace in C?
Take a look at this code:
Code:
int main(void) {
{
struct my_struct { int i; };
int i, j;
}
{
struct my_struct { char *s; };
}
return 0;
}
Although both are structure tags, is it correct to say that these two identical tags are in different namespaces?
So in the first block: my_struct is in one namespace; the two local variables in another; and the (only) member of my_struct in a third namespace; but the two structure tags are not in the same namespace, otherwise an error would occur.
#2 Why does the following compile?
Code:
#include <stdio.h>
int main(void) {
struct struct_t {
enum enum_t { A, B, C, D } my_enum;
int i;
double d;
} my_struct;
enum enum_t var = B; // HELP
printf("%d\n", D); // HELP
printf("%d\n", var);
return 0;
}
Before I compiled the code, I assumed that the enum constants were only known inside the struct, but it turned out that was not the case. Also, how can enum_t be accessible outside of struct_t?
How does it work?!
Thank you for help.