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

后端 未结 5 512
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 06:24

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 (pri         


        
5条回答
  •  Happy的楠姐
    2020-12-13 06:27

    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.

提交回复
热议问题