简体   繁体   中英

Using Unions of enums in C

I am using pointers to functions in state machines and need to pass an enumerated value that is built from aa union of enums. As I am using a table with functions calls I need their call/return values to match. I have tried to build this on my local box and on CodeChef using GCC C 4.9.2 With codeChef I'm getting the error:

prog.c: In function 'main': prog.c:12:15: error: expected expression before 'FOO' NewFooState(FOO.D); // <<<<<< This is what fails!!

typedef enum Foo_t {A, B, C, D} FOO;
typedef enum Bar_t {E, F, G} BAR;


typedef union FooBar_t {FOO Foo; BAR Bar;} FooBar;

FooBar NewFooState(FooBar NewState);

//I want to later make call such as

int main(){
  NewFooState(FOO.D);       // <<<<<< This is what fails!!
  return 0;
}
//and have that function look like:

FooBar NewFooState(FooBar NewState){
  static FooBar oldState = {.Foo=A};
  FooBar ReturnValue = oldState;
  oldState = NewState;
  switch (NewState.Foo){
      case A:
      case B:
      case C:
      case D:
        //stuff
        break;
  }
  return ReturnValue ;
}

Note the particular way that is needed to initialize oldState:

static FooBar oldState = {.Foo=A};

My problem seems to be using enum value such as FooBar.Bar.G I've tried all of the syntax combinations that see obvious to me such as {.Foo=G}, FooBar_t.Bar.G, Bar.G, G, etc but I can not get the compiler to accept it. I just want to use one of the enumerated values such as F and call the NewFooState function, such as NewFooState(F). Should be so simple... With NewFooState(G) I am getting the error Error[Pe167]: argument of type "enum G" is incompatible with parameter of type "FooBar"

There is no such thing as FOO.D . D is its own identifier which designates an enum value associated with FOO . However, your NewFooState() function expects a FooBar , not FOO (nor BAR ). So, you need a variable of the proper type. One way this can be done:

  FooBar FOO_D = { .Foo=D };
  NewFooState(FOO_D);

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