📜 ⬆️ ⬇️

Fun with the switch operator

I had a simple, working code (I removed the excess 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 big complaints about him, but decided to micro-optimize it:

Decided to eliminate redundancy and to make separately the general transformation.
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 great: 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 warnings, so I thought about what could be done here, and having remembered 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 was gone, but the code turned out to be unsupported, therefore, having last seen it, 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 weakened so that it only needs to be properly composed and case: labels must appear before statements.
Only the first break statement ; comes out of the switch construction, the rest go out of the do {} while loop .

I also know that the switch is used for the organization of coprocesses in C, but, unfortunately, an example of such a useful application of this feature could not be found.

Source: https://habr.com/ru/post/88863/


All Articles