gpt4 book ai didi

c - 为什么我们不能在不使用花括号的情况下在 switch case 冒号后声明变量?

转载 作者:太空宇宙 更新时间:2023-11-04 04:53:30 24 4
gpt4 key购买 nike

case 1:
{ //question is about this curly brace
int val;
scanf("%d", &val);
if(top1 == NULL){
enqueue(top1, val, bottom1);
}
else{
enqueue(top1, val);
}
break;
}

案例 1 后没有花括号:它给出了一个错误:*

a label can only be part of a statement and a declaration is not a statement: int val;

*

最佳答案

C 文法就是这样定义的。变量声明不被视为语句:

int x; //a declaration
int y = 3; //another declaration
x = y + 1; //a statement

标签后面必须有声明。不允许标签加声明。

foo: int x; //error
bar: x = y +1; //ok

也就是IMO,不方便:

while (...)
{
//...
goto end;
end: //error, no statement
}

记住 case 只是一种特殊的标签,所以:

case 1: int x; //error
case 2: x = y +1; //ok

大括号的问题在于,在 C 语言中,它们用于构建复合语句,这当然是一种语句。复合语句里面的行既可以是声明也可以是语句,都是混合的(旧的C版本只允许在开头声明,不能在中间声明)。所以:

case 1: int x; //error: label plus declaration
case 2: { int x; } //ok: label plus compound statement

作为脚注,由于现代 C 允许混合声明和语句,您还可以编写:

case 1:; int x; //ok: label plus empty statement.

因为孤立的 ; 是一个空语句,所以它可以用于满足需要无操作语句的语法。

是使用 ; 还是 { ... } 是一个可读性问题。在 end: 示例中,我将使用 ;,但在 case: 中,我更喜欢 {...}/.

while (...)
{
//...
goto end;
end:; //ok, empty statement
}

switch (...)
{
case 1: //ok, compound statement
{
int x;
}
}

当然可以写出更有创意的方案,比如:

case 1: {} int x; //ok, label plus empty compound statement

关于c - 为什么我们不能在不使用花括号的情况下在 switch case 冒号后声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12189359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com