[英]switch-case automatic break
Are there any C compilers with extensions that provide the ability to automatically break at the end of each case statement (similar to what Swift has available) or an alterate switch available in a future C spec? 是否有带有扩展名的C编译器能够在每个case语句的末尾自动中断(类似于Swift提供的功能)或将来的C规范中可用的替代开关?
Mostly interested in this to avoid clutter in extensive switch-case scenarios. 对此最感兴趣的是避免在广泛的开关情况下造成混乱。
I find this works "ok" but would prefer something clearer about the behavior. 我发现此方法“正常”,但希望更清晰地了解行为。
#define case break; { } case
#define switch_break switch
switch_break (action)
{
default: printf ("Unknown action");
case action_none : // Nothing
case action_copy : doCopy ();
case action_paste : doPaste ();
case action_none : break; /* C requires a statement after final case */
}
If you hate writing break
everytime, wrap the switch
statement inside a function. 如果您讨厌每次都写
break
,则将switch
语句包装在一个函数中。 Then break
can be replaced with return
statements. 然后
break
可以用return
语句代替。 For example 例如
int switch_func(char c) {
switch(c) {
case 'a': return 1;
case 'b': return 3;
case 'c': return 5;
case 'd': return 7;
. . .
default: return 0;
}
}
Reduces code only if return values are present. 仅当存在返回值时才减少代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.