简体   繁体   中英

enum in a struct; newbie in a c

I'm wondering about the syntax of using an enum in a struct ( in C )

I've seen various examples where a struct + union / enum combination was used to create a complex type, for example:

struct MyStruct{
    enum{
        TYPE_1,
        TYPE_2,
        TYPE_3,
    } type;
    union{
        int value_1;
        int value_2;
        int value_3;
    } value;
};

// ...

struct MyStruct test_struct;

Anyways, from this example, how would I store/test the current "type" as per the enum field?

If I have a pointer to test_struct , this doesn't seem to work; kicking back an unknown member error:

struct MyStruct *test_pointer = &test_struct;

test_pointer->value = test_pointer->VALUE_1;

I'm just curious, do I need to access the enum values as global values?

test_pointer->value = VALUE_1;

Any clarifications would be greatly appreciated.

The intended usage of such a struct would be something like that:

switch (test_struct.type) {
  case TYPE_1:
    printf("%d", test_struct.value.value_1);
    break;

  case TYPE_2:
    printf("%d", test_struct.value.value_2);
    break;

  case TYPE_3:
    printf("%d", test_struct.value.value_3);
    break;
}

Note that capitalising VALUE_1 , VALUE_2 and VALUE_3 is incorrect because they are not constants but rather members of the union.

TYPE_1 , TYPE_2 and TYPE_3 will be globally accessible, no matter that the corresponding enum resides in the struct.

What happens with a union is that all objects defined therein occupy the same memory. And it's illegal to read an object different than the last written one.

In

union blah {
    int bleh;
    double blih;
    char bloh[42];
};
union blah myobject;

myobject contains one of int , double , or char[] . And there is no indication which one is correct. The indication must be kept somewhere else by the programmer:

int lastblahwrite; /* 0: int; 1: double; 2: char[] */
strcpy(myobject.bloh, "The quick brown dog");
lastblahwrite = 2;

and later this could be used as

switch (lastblahwrite) {
    case 0: printf("%d\n", myobject.bleh); break;
    case 1: printf("%f\n", myobject.blih); break;
    case 2: printf("%s\n", myobject.bloh); break;
    default: assert(!"this didn't happen"); break;
}

Rather than have two separate variables, to make management easier, it is usual to group the union itself and the indicator variable in a struct, as in your example.

The management still has to be written by the programmer. Nothing is automatic.

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