Fun with the switch statement

    I had a simple, working code (I removed the unnecessary and left only the essence):
    typedef enum
      {
        enNone,
        enOne,
        enTwo,
        enThree
      }TEnum;
        switch(Enum)
          {
            case enNone:
                 /*Ничего не делаем*/
                 break;/*enNone*/
            case enOne:
                 Value=f1(Value);
                 Value=A*Value+B;
                 break;/*enOne*/
            case enTwo:
                 Value=f2(Value);
                 Value=A*Value+B;
                 break;/*enTwo*/
            case enThree:
                 Value=f3(Value);
                 Value=A*Value+B;
                 break;/*enThree*/
          }/*SWITCH*/
    


    I had no major complaints against him, but I decided to micro-optimize him:

    I decided to eliminate redundancy and make a general transformation separately.
    It turned out like this:
        if(enNone!=Enum)
          {
            switch(Enum)
              {
                case enOne:
                     Value=f1(Value);
                     break;/*enOne*/
                case enTwo:
                     Value=f2(Value);
                     break;/*enTwo*/
                case enThree:
                     Value=f3(Value);
                     break;/*enThree*/
              }/*SWITCH*/
            Value=A*Value+B;
          }/*THEN*/
    


    Everything is wonderful: the code has become more compact, the correctness of the code has not deteriorated, but the compiler began to issue a warning that in the switch statement one of the enumeration constants is not processed.

    I try to program so that there are no warning, so I thought about what can be done here, and remembering Duff ’s device , I did this:

        switch(Enum)
          {
            case enNone: break;
            do
              {
                case enOne:
                     Value=f1(Value);
                     break;/*enOne*/
                case enTwo:
                     Value=f2(Value);
                     break;/*enTwo*/
                case enThree:
                     Value=f3(Value);
                     break;/*enThree*/
              }while( 0 );
            Value=A*Value+B;
          }/*SWITCH*/
    


    The warning disappeared, but the code turned out to be unsupported, so, after admiring the last time, I rolled back to the original version.

    This code only works because in the C language for the switch statement, the restrictions on the compound statement are so relaxed that it only needs to be correctly composed and the case labels are before the statements.
    Only the first break statement ; exits the switch construct , the rest exits the do {} while loop .

    I also know that such a switch feature is used to organize co-processes in C, but, unfortunately, an example of such a useful application of this feature could not be found.

    Also popular now: