C switch 语句中的最终子句(可能使用 goto)
我可以在 C 开关中使用类似 javas finally 子句的东西。我的大多数案例都有一组共享的功能,我想将其放在一个案例中。我正在考虑使用 goto 语句来实现这一点,充分了解 goto 代码混淆能力,将共享案例放在 switch 语句的底部似乎仍然是比将共享功能分区到单独函数中更“干净”的方法。
无论如何,我一直在尝试这样做:
switch( x ) {
case 0:
printf("Case 0\n");
goto case 2;
break;
case 1:
printf("Case 1\n");
goto case 2;
break;
case 2:
printf("Case 2\n");
break;
default:
// do nothing
break;
}
但是,使用 gcc,这会失败并出现错误
error: expected identifier or ‘*’ before ‘case’
关于如何使其工作的任何建议?或者可能有更好的方法?
I could use something like javas finally clause in a C switch. Most of my cases has a shared set of functionality that I would like to put a single case. I was thinking of implementing this using goto statements, being well aware of gotos code obfuscation ability, putting the shared case at the bottom of the switch statement still seems a "cleaner" way to do this than partitioning the shared functionality into a seperate function.
Anyway, I have been trying to do it something like this:
switch( x ) {
case 0:
printf("Case 0\n");
goto case 2;
break;
case 1:
printf("Case 1\n");
goto case 2;
break;
case 2:
printf("Case 2\n");
break;
default:
// do nothing
break;
}
However, using gcc, this fail with the error
error: expected identifier or ‘*’ before ‘case’
Any suggestions on how to make it work? Or possibly a better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
“最佳实践”当然是将共享代码委托给函数。但在某些情况下,这是过度设计的,或者根本不可能/不可取的,那么你可以这样做:
我不觉得这太难以阅读,而且我对此没有任何问题,只要整个声明适合一个屏幕(否则它就相当于意大利面条代码)。但是,您可能必须在代码审查中捍卫它,这是我放弃此类构造并重新思考代码的主要原因之一。
The "best practice" is of course to delegate the shared code to a function. But in some situations where this is overengineering, or simply not possible / desirable, then you can do:
I don't find this too unreadable, and I don't have any problem with it, provided the whole statement fits in one screen (otherwise it qualifies as spaghetti code). However, you may have to defend it in code reviews, which is one of the main reasons I would step away from such constructs and rethink the code.
为什么不将公共代码放在开关之后?
我觉得我必须更新此回复,用我认为有更好设计的答案来解释已接受的答案:
或者,您当然可以在“默认”情况下设置一个标志,这将阻止通用代码执行,如果您对某些原因不想将其分解为单独的函数。
Why not put the common code after the switch?
I feel I have to update this reply, paraphrasing the accepted answer with one I feel has a better design:
Or, you could of course set a flag in the 'default' case that would prevent the common code from executing, if you for some reason don't want to break it out to a separate function.
您可以使用标志
do2
,根据需要设置它并在切换后检查它。如果它更复杂且具有许多层次依赖性,则构建一个具有转换的状态机。
you could use a flag
do2
, set it if needed and check it after the switch.if it is more complex with many hierarchical dependencies then build a state machine with transitions.
我宁愿采用这种方法:
I'd rather going for this approach:
以下作品:
Following works: