enum in a struct; newbie in a c

≯℡__Kan透↙ 提交于 2019-12-12 15:03:12

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5902744/enum-in-a-struct-newbie-in-a-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!