49

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?

7
  • Is your "most bizarre" switch statement Duff's Device?
    – sarnold
    Nov 14, 2011 at 6:26
  • No, it is not. I'll add the code sample for those who do not have access to H&S5. And Duff's Device requires braces! Nov 14, 2011 at 6:40
  • 3
    Nice example. I don't think that the missing braces are the particularity, here. Your example also would work with braces. The thing which is unconventional here is to have the switch label a different logical levels of a statement. Nov 14, 2011 at 7:27
  • 2
    @JensGustedt Yes, it would work with braces, but it's the only one I've seen so far that works without them and still seems to serve a purpose. Nov 14, 2011 at 7:50
  • 1
    For the sake of documentation, "H&S5" is the fifth edition of Samuel Harbison and Guy Steele's C: A Reference Manual. (I didn't know and had to track it down by searching for the code fragment.)
    – texdr.aft
    Dec 9, 2020 at 11:11

5 Answers 5

13

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
}

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.

7
  • +1 Good one, never seen it like this. I'd add the default: label at the end, but that's not necessary. But then: Even if the switch was using braces, the if/else pairing would remain correct IMHO. Nov 14, 2011 at 8:42
  • 1
    @JohanBezem, no I don't think it would be correct since this then would expand to something like { ... }; and so the if as a whole would be terminated by the ; Nov 14, 2011 at 10:03
  • 2
    Does the "switch" statement in your example offer any benefit over the do{this;that;the_other;}while(0) pattern? The latter is what I would consider the normal idiomatic way to write a pseudo-function macro in scenarios where I can't write them as a dummy rvalue (e.g. #define begin_write(x) (write_mode=1,begin_read_or_write((x))).
    – supercat
    Nov 20, 2011 at 21:13
  • 1
    Wrapping a macro in do{...}while(0) means that one can write multiple statements within the macro without having to worry about how it will interact syntactically with outside code. When I see "do{} at the start of any macro, I look for the "...while"; if it's "while(0)", I interpret the do/while construct as a "statement guard". In the case of your DEBUG_PRINT macro, it may be possible to use the && or ?: operator so the whole macro would be an expression rather than a statement (not sure which formulation would yield the best code without superfluous warnings).
    – supercat
    Nov 20, 2011 at 22:27
  • 1
    I'm not clear in what cases the "switch" statement would be better than using either conditional operators or a do/while guard. The former would mean the macro could be embedded within a larger expression, while the latter would allow the macro to be expanded to contain multiple statements without difficulty. The switch formulation offers neither of these advantages; does it offer some other advantage I'm not seeing?
    – supercat
    Nov 20, 2011 at 22:29
4

Here's an example written by Dennis Ritchie in 1972 during his work on the first C compiler. The c02.c module, linked at the foot of page I just linked to, includes

easystmt()
{
    extern peeksym, peekc, cval;

    if((peeksym=symbol())==20)  /* name */
        return(peekc!=':');  /* not label */
    if (peeksym==19) {      /* keyword */
        switch(cval)
        case 10:    /* goto */
        case 11:    /* return */
        case 17:    /* break */
        case 18:    /* continue */
            return(1);
        return(0);
    }
    return(peeksym!=2);     /* { */
}

From reading his 1972 code it's clear Dennis was a fan of switch statements - he used them quite a bit. It's not so surprising given that almost everything was encoded as an int partly for lack of other data type possibilities. His compiler implementation used no structs at that stage because he was just in the middle of adding them to the language. Dynamic dispatch, vtables and polymorphism were a long way off. I've tried and failed to find a reference for this but if I recall correctly Dennis "invented" switch statements or at least contributed ideas leading to the form they take in C and considered them one of his best or proudest additions to the language.

The ability to leave out the braces makes switch statements formally similar to if, for, do and while statements, helping to simplify and unify the grammar. See the selection-statement and iteration-statement productions in the C grammar (e.g. in Appendix A13 of Kernighan and Ritchie, pages 236-237 in my copy) where these things are defined.

Obviously one can always add braces but maybe that seems heavy for such simple examples as this one. This example could be coded as a disjunctive if statement but I think one of the ideas Dennis had for switch was that the compiler is more clearly being offered the opportunity to optimise the implementation of the branching logic based on the particular constants involved.

2

I've thought of another case.

Suppose I have a counter of type unsigned char indicating the number of iterations of a loop, but if the counter equals zero, it needs to go through the loop 256 times. If my thinking is correct, you could code this as follows:

uint8_t counter;
/* counter will get its value here somewhere */
switch (counter)
    default:
        while (0 < counter)
        {
            case 0:
                /* Perform action */
                counter--;
        }

This of course assumes that underflow from 0x00 results in 0xFF for an unsigned char. But it does for all my environments, even though PC Lint will complain... And yes, it contains braces, but just for the while, not for the switch. If you know something better, let me hear it!

Would I program like this? Never! ... well, on a small 8-bit processor I even might! :-)

5
  • And yes, I do know that you can achieve the same using a do/while, but that was not the point of this question... Nov 14, 2011 at 9:31
  • Hm, I think that you are more fascinated by the non-serial control flow than by the fact that this is just a statement and not a block. This again could be done with an enclosing {}, no? Nov 14, 2011 at 11:59
  • Yes, it could, just like the original H&S5 example. I'm working on creating a special training for really experienced C programmers, and for that I'm looking into the edges of the language and beyond. Nov 14, 2011 at 12:56
  • Ah, I see. But for that the aspect of jumping at different levels of control structures is much more important than having braces or not as you asked in your question. Nov 14, 2011 at 13:36
  • 1
    Well, I'd assume my target audience to know that jumping at different levels of control structures is possible. Several if not many will even have done so at some time in the past. But indulging in your regular and personal programming style, you tend to lose sight of the basics. Or did you re-read the C BNF-grammar in full lately, registering all the consequences, be they good or bad? I didn't... *grin* I would like to wake my audience by using some striking illustrations, even (or especially) if they are considered bad style. Nov 14, 2011 at 14:34
-1

Section 6.8.4.2 The switch statement says:

A switch statement causes control to jump to, into, or past the statement that is the switch body, depending on the value of a controlling expression, and on the presence of a default label and the values of any case labels on or in the switch body. A case or default label is accessible only within the closest enclosing switch statement.

The terms switch-body and closest enclosing switch-statement seem not to require braces. So you're right it looks weird but is legal. (Never saw that before)

1
  • 1
    Of course, braces are usually required, and more than useful. But not necessary. I added the sample. Case labels belonging to the switch(x) can be placed until just before the semi-colon after process_composite(x), which is the end of the indicated switch body. Nov 14, 2011 at 6:52
-1

In practice switches are used with braces (even in Duff's device) for readability reasons. And adding braces does no harm.

1
  • 2
    That was not the question, sorry. I know that, and I will not accept any other code in my area of responsibility. However, I'm interested in the edges of the language definition. Nov 14, 2011 at 6:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.