简体   繁体   English

在 C 中使用枚举联合

[英]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:我试图在我的本地机器和 CodeChef 上使用 GCC C 4.9.2 和 codeChef 构建它,我收到错误:

prog.c: In function 'main': prog.c:12:15: error: expected expression before 'FOO' NewFooState(FOO.D); prog.c: 在函数 'main' 中:prog.c:12:15: 错误:'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:请注意初始化 oldState 所需的特定方式:

static FooBar oldState = {.Foo=A};静态 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.我的问题似乎是使用枚举值,例如FooBar.Bar.G我已经尝试了所有对我来说显而易见的语法组合,例如 {.Foo=G}、FooBar_t.Bar.G、Bar.G、G,等等,但我无法让编译器接受它。 I just want to use one of the enumerated values such as F and call the NewFooState function, such as NewFooState(F).我只想使用枚举值之一(例如 F)并调用 NewFooState 函数,例如 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"应该如此简单......使用 NewFooState(G) 我收到错误 Error[Pe167]: “enum G”类型的参数与“FooBar”类型的参数不兼容

There is no such thing as FOO.D .没有FOO.D这样的东西。 D is its own identifier which designates an enum value associated with FOO . D是它自己的标识符,它指定与FOO关联的枚举值。 However, your NewFooState() function expects a FooBar , not FOO (nor BAR ).但是,您的NewFooState()函数需要FooBar ,而不是FOO (也不是BAR )。 So, you need a variable of the proper type.因此,您需要一个正确类型的变量。 One way this can be done:一种方法可以做到这一点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM