简体   繁体   中英

Accessing an enum inside a struct in C

#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.).

Yes, by simply writing the name defined.

#include <stdio.h>

typedef struct test {
 enum en{
    zero, one
 } en;
} test;

int main(){
 test t;
 t.en = one;
 return 0;
}

Structure do not introduce a separate scope in C.

Note also that using en as both the enum tag and variable name is perfectly fine in C, but somewhat confusing in C++.

Here is a modified version that should compile as C and C++:

#include <stdio.h>

#ifdef __cplusplus
#define SCOPED_ENUM(s,e) s::e
#else
#define SCOPED_ENUM(s,e) e
#endif

typedef struct test {
    enum en {
        zero, one
    } en;
} test;

int main() {
    test t;
    t.en = SCOPED_ENUM(test, one);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM