如果我的措辞错了,请道歉.
我从高中开始就被教过,在if,while,for等语句之后添加大括号,只要有多行代码可以执行.例:
while(i<12)
i++;
z = i+3;
cout << "Answer is " << z << endl;
Run Code Online (Sandbox Code Playgroud)
不会执行你期望的.但以下将:
while(i<12){
i++;
z = i+3;
cout << "Answer is " << z << endl;
}
Run Code Online (Sandbox Code Playgroud)
但是我最近遇到了一个while循环,其中包含一个if..else语句,看起来好像不止一行代码/语句,然而它执行并按原样运行,无论它是否有大括号用于其作用域或不.
while(current != NULL && !found)
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
Run Code Online (Sandbox Code Playgroud)
这是为什么?它是否将if..else语句视为单个语句?
Nat*_*ica 12
if .. else是C++中的单个语句(技术上称为选择语句).Per [stmt.select]/1的有效形式if是:
Run Code Online (Sandbox Code Playgroud)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;
}
Run Code Online (Sandbox Code Playgroud)
也是一个单一的陈述,行为正确.
| 归档时间: |
|
| 查看次数: |
299 次 |
| 最近记录: |