是否有使用没有括号switch语句有用的呢? [英] Is there a useful case using a switch statement without braces?

查看:309
本文介绍了是否有使用没有括号switch语句有用的呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在的H& S5我遇到不使用大括号最离奇的switch语句(8.7.1,第277)结果。
这里的样本:

In H&S5 I encountered the "most bizarre" switch statement (8.7.1, p. 277) not using braces.
Here's the sample:

switch (x)
    default:
    if (prime(x))
        case 2: case 3: case 5: case 7:
            process_prime(x);
    else
        case 4: case 6: case 8: case 9: case 10:
            process_composite(x);

这个想法似乎是避免的开销素(X)为最常见的小数字。

当我看到这句话,我感到困惑缺少的括号,但检查语法官方(的 C1X pre-标准,6.8.4,第147页),语法是正确的:switch语句只是有开关前pression和右括号后的声明。

When I saw that statement, I was confused about the missing braces, but checking the official grammar (C1X pre-standard, 6.8.4, p. 147), the syntax was correct: A switch statement just has a statement after the switch expression and the closing parenthesis.

但在我的编程实践我再也没​​有遇到过这种奇怪的switch语句(我不希望看到任何在code,我必须承担责任),但我就开始琢磨:

But in my programming practice I never again encountered such a curious switch statement (and I wouldn't want to see any in code that I have to take responsibility for), but I started wondering:

是否有任何的你知道这种开关的前pression,一个没有使用大括号,但仍然有意思呢?不仅仅是开关(I); (这是合法的,但一个NOP),但使用具有某种有用的目的至少有两个case标签

Would any of you know such a switch expression, one without using braces, but still having meaning? Not just switch (i); (which is legal, but a NOP), but using at least two case labels having some sort of useful purpose?

推荐答案

如果您使用控制结构中宏开关的而不是如果来得心应手,因为它没有晃来晃去其他的问题。

If you use control structures in macros a switch instead of if comes handy since it has no dangling else problem.

#define DEBUG_PRINT(...) switch (!debug_mode) case 0: fprintf(__VA_ARGS__)

随着你没有惊喜,如果宏观的用户将在这一个附加条件

With that you don't have surprises if a user of that macro puts this in an additional condition

if (unclear) DEBUG_PRINT(stderr, "This is really %unclear\n", unclear);
else {
 // do something reasonable here
}

这样的调试宏有被总是被编译(并最终优化掉)的优势。因此,调试code具有通过该计划的所有活动时间仍然有效。

Such a debug macro has the advantage of being always compiled (and then eventually optimized out). So the debug code has to remain valid through all the live time of the program.

此外观察这里,这是很重要的开关不使用 {} ,否则的if / else 例子将不能工作。所有这一切都可以通过其他方式(的if / else (无效)0 实现做/而技巧),但是这一个是最方便的,我知道的。

Also observe here that it is important that the switch doesn't use {}, otherwise the if/else example wouldn't work either. All this could be achieved by other means (if/else , (void)0 and do/while tricks) but this one is the most convenient I know of.

和不带我错了,我就不多说了,每个人都应该使用内宏控制结构,你一定要知道自己在做什么。但也有它是合理的情况。

And don't take me wrong, I don't say that everybody should use control structures inside macros, you certainly should know what you are doing. But there are situations where it is justified.

这篇关于是否有使用没有括号switch语句有用的呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆