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

标签 c++

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

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

相关文章:

尝试从双链表打印数据时 C++ 程序崩溃

c++ - CUDA 流破坏和 CudaDeviceReset

C++ fwrite 不写入文本文件,不知道为什么?

c++ - 在 MainWindow 中看不到我的标签和布局

c++ - 最佳实践 - 在单元测试中链接到 lib 或编译源代码

c++ - 将源代码翻译成外语

c++ - STL 并行搜索算法的保证

C++ 传递 typedef

c++ - 在常量表达式中使用 numeric_limits::max()

c++ - Log4Cpp.properties 文件不存在错误