gpt4 book ai didi

C 嵌套开关 : outer switch's case inside inner switch

转载 作者:太空宇宙 更新时间:2023-11-04 00:19:47 24 4
gpt4 key购买 nike

我正在为我正在编写的解释器添加协程支持,并且我想执行如下操作:

typedef enum {
bar_stuff,
bar_other
} Bar;

typedef enum {
foo_error=-1,
foo_none=0,
foo_again
} Foo_state;

Foo_state do_foo(Bar bar,Foo_state foo)
{
switch(foo)
{
case foo_none: //start
switch(bar)
{
case bar_stuff:
//do stuff
return foo_none;
case bar_other:
//do other stuff
return foo_again;
case foo_again: //!! this doesn't work
/* edit: this is supposed to be a case of
* switch(foo), not switch(bar)
*/
//do more other stuff
return foo_none;
default:
//stuff
return foo_none;
}
default:
//fail
return foo_error;
}
}

显然这行不通(我得到重复的案例值,替代方案可能是未定义的行为/段错误)。我可以将 switch(bar) 写成 if/else if/else 链,但我希望有更好的方法。

如果有不同,我正在使用 gcc。

编辑:

以下内容可行,但需要维护 PITA:

Foo_state do_foo2(Bar bar,Foo_state foo)
{
switch(foo)
{
case foo_none: goto case_foo_none;
case foo_again: goto case_foo_again;
default:
//fail
return foo_error;
}
case_foo_none: //start
switch(bar)
{
case bar_stuff:
//do stuff
return foo_none;
case bar_other:
//do other stuff
return foo_again;
case_foo_again:
//do more other stuff
return foo_none;
default:
//stuff
return foo_none;
}
}

编辑 2:

好吧,这似乎并没有产生前面提到的“更好的方法”,所以我想知道是否有人预见到这样写会有问题:

Foo_state do_foo3(Bar bar,Foo_state foo)
{
switch(foo)
{
case foo_none: //start
if(bar == bar_stuff)
{
printf("do stuff\n");
return foo_none;
}
else if(bar == bar_other)
{
printf("do other stuff\n");
return foo_again;
case foo_again: //continue
printf("do more other stuff\n");
return foo_none;
}
else
{
printf("stuff\n");
return foo_none;
}
default:
//fail
return foo_error;
}
}

我看到的问题是缺少一个 bar_* 值(因为有几个这样的函数,而且一些枚举有几十个值),但我想一个测试脚本应该可以工作......

最佳答案

你也可以只把 { } 放在每个 case: statement
没有它们,整个案例堆栈将作为一个单元进行评估,因此不能在一个案例中定义任何变量:

但是通过放置

 case blah:
{
// do stuff
}
break;

你可以在 case 语句中放入任何你想要的东西。

关于C 嵌套开关 : outer switch's case inside inner switch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1978202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com