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?
If you use control structures in macros a
switchinstead ofifcomes handy since it has no danglingelseproblem.With that you don’t have surprises if a user of that macro puts this in an additional condition
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
switchdoesn’t use{}, otherwise theif/elseexample wouldn’t work either. All this could be achieved by other means (if/else,(void)0anddo/whiletricks) 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.