Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the point of switch (…) while (0)?

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the C standard a statement is defined as one of these

A.2.3 Statements

(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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading