#include <stdio.h>
typedef struct test {
enum en {
zero, one
} en;
} test;
int main(){
test t;
// t.en = test::one; <-- How can I accomplish this?
return 0;
}
test::one
is a C++
syntax and won't compile in C
.
Is it possible to access en
from outside the struct in C?
I know I can use integers here like t.en = 1;
but I'm trying to use enum values.
In C, a struct
does not create a new namespace for types - the fact that you defined enum en
within the body of the struct definition makes no difference, that tag name is visible to the remainder of the code in the program. It's not "local" to the struct
definition. Same with a nested struct
type - if declared with a tag, such as
struct foo {
struct bar { ... };
...
};
struct bar
is available for use outside of struct foo
.
C defines four types of namespaces - one for all labels (disambiguated by the presence of a goto
or :
), one for all tag names (disambiguated by the presence of the struct
, union
, or enum
keywords), one for struct
and union
member names (per struct
or union
definition - disambiguated by their presence in a struct
or union
type definition, or by the presence of a .
or ->
member selection operator), and one for all other identifiers (variable names, external (function) names, typedef names, function parameter names, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With