Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c - Is there a useful case using a switch statement without braces?

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);

The idea seems to be to avoid the overhead of prime(x) for the most common small numbers.

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.

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:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", unclear);
else {
 // do something reasonable here
}

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...