= newItem) -6ren">
gpt4 book ai didi

c++ - "if else"是否被视为单个语句?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:06:28 24 4
gpt4 key购买 nike

如果我的措辞有误,请见谅。

我从高中开始就被教导要在 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/

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