作者:嘉洲仔- | 来源:互联网 | 2022-12-05 17:42
如果我的措辞错了,请道歉.
我从高中开始就被教过,在if,while,for等语句之后添加大括号,只要有多行代码可以执行.例:
while(i<12)
i++;
z = i+3;
cout <<"Answer is " <
不会执行你期望的.但以下将:
while(i<12){
i++;
z = i+3;
cout <<"Answer is " <
但是我最近遇到了一个while循环,其中包含一个if..else语句,看起来好像不止一行代码/语句,然而它执行并按原样运行,无论它是否有大括号用于其作用域或不.
while(current != NULL && !found)
if(current->info >= newItem)
found = true;
else
{
trailCurrent = current;
current = current->link;
}
这是为什么?它是否将if..else语句视为单个语句?
1> NathanOliver..:
if .. else是C++中的单个语句(技术上称为选择语句).Per [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;
}
也是一个单一的陈述,行为正确.
@TimKlein A*语句*部分定义为*attribute-specifier-seq-opt selection-statement*,因此它是一个语句.仅仅因为它包含语句并不意味着它不是一个.