Enumeration in the structure; new to c

I'm curious about usage syntax enumin struct(in C)

I saw various examples in which the struct+ union/ combination was used to create a complex type enum, 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;

In any case, from this example, how can I store / test the current "type" according to the field enum?

If I have a pointer to test_struct, this does not work; discarding an unknown element error:

struct MyStruct *test_pointer = &test_struct;

test_pointer->value = test_pointer->VALUE_1;

I'm just wondering, do I need to access values enumas global values?

test_pointer->value = VALUE_1;

Any clarification would be greatly appreciated.

+3
source share
2 answers

:

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;
}

, VALUE_1, VALUE_2 VALUE_3 , , .

TYPE_1, TYPE_2 TYPE_3 , , enum .

+6

, , , , . , .

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

myobject int, double char[]. . :

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

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;
}

, , , , .

- . .

+1

All Articles