在 C 中使用枚举联合
Using Unions of enums in C
我在状态机中使用指向函数的指针,并且需要传递一个从枚举联合构建的枚举值。当我使用带有函数调用的 table 时,我需要它们的 call/return 值匹配。我试图在我的本地机器和 CodeChef 上使用 GCC C 4.9.2 和 codeChef 构建它,我收到错误:
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 ;
}
注意初始化 oldState 所需的特定方式:
static FooBar oldState = {.Foo=A};
我的问题似乎是使用枚举值,例如 FooBar.Bar.G 我已经尝试了所有对我来说显而易见的语法组合,例如 {.Foo= G}、FooBar_t.Bar.G、Bar.G、G 等,但我无法让编译器接受它。我只想使用其中一个枚举值(例如 F)并调用 NewFooState 函数,例如 NewFooState(F)。应该这么简单...
使用 NewFooState(G) 我收到错误 Error[Pe167]: argument of type "enum G" is incompatible with parameter of type "FooBar"
没有FOO.D
这样的东西。 D
是它自己的标识符,它指定与 FOO
关联的枚举值。但是,您的 NewFooState()
函数需要 FooBar
,而不是 FOO
(也不是 BAR
)。因此,您需要一个正确类型的变量。一种方法可以做到这一点:
FooBar FOO_D = { .Foo=D };
NewFooState(FOO_D);
我在状态机中使用指向函数的指针,并且需要传递一个从枚举联合构建的枚举值。当我使用带有函数调用的 table 时,我需要它们的 call/return 值匹配。我试图在我的本地机器和 CodeChef 上使用 GCC C 4.9.2 和 codeChef 构建它,我收到错误:
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 ;
}
注意初始化 oldState 所需的特定方式:
static FooBar oldState = {.Foo=A};
我的问题似乎是使用枚举值,例如 FooBar.Bar.G 我已经尝试了所有对我来说显而易见的语法组合,例如 {.Foo= G}、FooBar_t.Bar.G、Bar.G、G 等,但我无法让编译器接受它。我只想使用其中一个枚举值(例如 F)并调用 NewFooState 函数,例如 NewFooState(F)。应该这么简单... 使用 NewFooState(G) 我收到错误 Error[Pe167]: argument of type "enum G" is incompatible with parameter of type "FooBar"
没有FOO.D
这样的东西。 D
是它自己的标识符,它指定与 FOO
关联的枚举值。但是,您的 NewFooState()
函数需要 FooBar
,而不是 FOO
(也不是 BAR
)。因此,您需要一个正确类型的变量。一种方法可以做到这一点:
FooBar FOO_D = { .Foo=D };
NewFooState(FOO_D);