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; case enOne: Value=f1(Value); Value=A*Value+B; break; case enTwo: Value=f2(Value); Value=A*Value+B; break; case enThree: Value=f3(Value); Value=A*Value+B; break; }
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; case enTwo: Value=f2(Value); break; case enThree: Value=f3(Value); break; } Value=A*Value+B; }
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; case enTwo: Value=f2(Value); break; case enThree: Value=f3(Value); break; }while( 0 ); Value=A*Value+B; }
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.