Chi*_*roh 4 c switch-statement
我最近发现这switch (...) while (0) {}在 C 中是合法的(此处),但我找不到关于这件事的解释。
我在互联网上唯一一次看到这个是在混淆的 GitHub 存储库中,没有任何解释。
我所有的研究显然都给了我关于 while 或 switch 循环的结果,甚至没有提到这种语法,所以我想这更多是合法的,但非常罕见且可能无用,是对标准的滥用。谁能帮助我理解这一点?
编辑:正如@phuclv答案中所解释的,switch语句需要一个选择语句,它可以是括号内的一些代码(在这种情况下......可能是case语句)或一个带有自己的括号等的循环,这意味着这个在 C 中是合法的:
switch (...) while (...) switch (...) {}
Run Code Online (Sandbox Code Playgroud)
switch根本不关心后面的语句,它似乎只寻找 case(s) 和/或默认值。
switch (1) while (0) {
puts("Not executed");
}
Run Code Online (Sandbox Code Playgroud)
该puts语句不会被执行,因为没有 case/default,所以 switch 在这里基本上没有用。你可以在Compiler Explorer上看到它,GCC 给出警告并删除了开关。
但是,请注意:
#include <stdio.h>
int main(void) {
switch (1) while (1) switch (0) {
case 1:
puts("hello");
}
}
Run Code Online (Sandbox Code Playgroud)
没有显示任何内容,程序立即退出,因为 switch (1) 没有 case 1 或 default 语句。如果我们添加一个:
switch (1) case 1: while (1) switch (0)
Run Code Online (Sandbox Code Playgroud)
该程序无限循环,因为最嵌套的循环是 switch (0),没有 case 0 或 default。
结论:这while (0)只是一种滥用,除了混淆之外没有任何用处,但这仍然是一件有趣的事情。
在 C 标准中,语句被定义为以下之一
(6.8)声明:
Run Code Online (Sandbox Code Playgroud)labeled-statement compound-statement expression-statement selection-statement iteration-statement jump-statement
switch是一个selection-statement被定义为具有这样的语法
(6.8.4)选择语句:
Run Code Online (Sandbox Code Playgroud)if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement
因此switch接收一个expression并执行 the statement,这通常是 thecompound-statement {}但它可以是任何语句,包括iteration-statement
(6.8.2) 复合语句:
{ 块项目列表选择}(6.8.5) 迭代语句:
while(表达式)语句 do 语句 while ( 表达式 ) ; for ( 表达式opt ; 表达式opt ; 表达式opt ) 语句 for (声明表达式opt ;表达式opt ) 语句
switch语句跳转到labeled-statement(这也是一个普通的语句)并且它不关心子语句内的内容,编译器只会生成一个计算跳转到匹配case的expression
(6.8.1) 标记语句:
Run Code Online (Sandbox Code Playgroud)identifier : statement case constant-expression : statement default : statement