Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing an enum inside a struct in C

Tags:

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.

like image 851
Dan Avatar asked Jan 24 '23 08:01

Dan


1 Answers

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

like image 171
John Bode Avatar answered Feb 01 '23 03:02

John Bode