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 ?
EDIT : As explained in @phuclv answer, a switch statement expects a selection statement right after, which can be brackets with some code inside (in this case... likely case statements) or a loop with its own brackets etc, it means this is legal in C :
switch (...) while (...) switch (...) {}
switch
doesn't care at all about what statement follows, it only seems to look for case(s) and / or default.
switch (1) while (0) {
puts("Not executed");
}
The puts
statement isn't executed because there's no case / default, so the switch is basically useless here.
You can see it on Compiler Explorer, GCC gives a warning and removed the switch.
However, beware :
#include <stdio.h>
int main(void) {
switch (1) while (1) switch (0) {
case 1:
puts("hello");
}
}
Nothing is displayed and the program is exited instantly, because the switch (1) has no case 1 or default statement. If we add one :
switch (1) case 1: while (1) switch (0)
The program loops indefinitely because the most nested loop is switch (0) with no case 0 or default.
Conclusion : The while (0)
is only an abuse and has no utility except obfuscation, but that's still an interesting thing to know.