I recently discovered that switch (...) while (0) {} is legal in C (here), but I cannot find an explanation about this thing.
The only other time I saw this in the Internet is in an obfuscation GitHub repository, without any explanation.
All my researches obviously gave me results about while or switch loops, without even mentioning this syntax, so I guess it’s more something legal but very rare and likely useless, an abuse of the standard.
Can anyone help me understand this ?
>Solution :
In the C standard a statement is defined as one of these
(6.8) statement:
labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement
switch is a selection-statement which is defined to have syntax like this
(6.8.4) selection-statement:
if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
So switch receives an expression and do the statement, which is normally the compound-statement {} but it can be any statement including the iteration-statement
(6.8.2) compound-statement:
{ block-item-listopt }(6.8.5) iteration-statement:
while ( expression ) statement do statement while ( expression ) ; for ( expressionopt ; expressionopt ; expressionopt ) statement for ( declaration expressionopt ; expressionopt ) statement
switch statement jumps to the labeled-statement (which is also a normal statement) and it doesn’t care about the content inside the sub statement, the compiler will just generate a computed jump into the case matching expression
(6.8.1) labeled-statement:
identifier : statement case constant-expression : statement default : statement