如果我的措辞有误,请见谅。
我从高中开始就被教导要在 if、while、for 等语句之后添加大括号,只要要执行的代码不止一行。示例:
while(i<12)
i++;
z = i+3;
cout << "Answer is " << z << endl;
不会执行您所期望的。但以下将:
while(i<12){
i++;
z = i+3;
cout << "Answer is " << z << endl;
}
然而,我最近遇到了一个 while 循环,其中包含一个 if..else 语句,看起来像不止一行代码/语句,但它执行并按应有的方式工作,无论它是否有花括号它的范围与否。
while(current != NULL && !found)
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
这是为什么呢?它是否将 if..else 语句视为单个语句?
最佳答案
if .. else 是 C++ 中的单个语句(技术上称为 selection statement )。每[stmt.select]/1 if
的有效形式是:
selection-statement: if constexpr-opt ( init-statement-opt condition ) statement if constexpr-opt ( init-statement-opt condition ) statement else statement
所以
while(current != NULL && !found)
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
也是一个单一的声明并且行为正确。
关于c++ - "if else"是否被视为单个语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52172268/