为什么 C++ 在 if 语句中提供声明?

Why does C++ offer declarations in if statements?

我最近了解到 if statements 可用于在 C++ 中 声明变量 。我个人真的不明白背后的原因。

不应该 if statements 只检查 条件是否正确 ,并且声明变量会导致错误?

也就是说,据我所知,if statements 只能 比较两个单独的值。所以在 if statement 中声明任何东西真的没有意义,因为你没有 比较 任何东西。

原文Post:

为什么 c++ 编译器接受这个:

#include <iostream>

int Test()
{
    return 10;
}

int main()
{
    if (int n = Test())
    {
        std::cout << "hi";
    }
}

更具体地说:为什么 if (int n = Test()) 是一个有效的语句?

基本上是shorthand的写法:

{
    int n = Test();
    if (n != 0)
    {
        std::cout << "hi";
    }
}

所以,如果 Test() returned 0 那么我们不进入 if 块,否则我们进入 n 立即阅读它做了什么 return,但仅在 if 的范围内。

请注意,本例中的整数值可以被视为布尔值,其中 0 == false 和其他任何值都是 true

您在if语句中输入的条件表达式是一个操作。 如果运算成功(即声明了n并填入10),则其值为true。所以它会编译并且 if 语句将是 运行.

Who would use int n = Test() as an if statement?

限制了n的范围,在if声明中,谁要这个谁就得。


现在如果你问:

"Why can you declare and initialize and use a variable like that?"

这是有效的,因为 C++ 标准是这么说的。 if-statement,语法

attr(optional) if ( condition ) statement-true else statement-false

....
condition

init语句的原因是为了限制变量的范围,并允许重用函数返回的值。 C++17 为 iffor-each 引入了专用的 init 语句 有时您可能想在使用它返回的值之前通过返回 0 或 nullptr 来检查函数是否失败并且您不想污染范围。

void foo()
{
   if(int var = some_function(); var != 0)
   {
      // use var
      use_var(var);
   }
   else throw std::exception();
}

它在 if 语句中可能不那么常见,但在 for-each 语句中更容易派上用场。看这个例子。

struct test
{
   std::vector<int> elements;
   auto& items()
   {
      return elements;
   }
}

test get_test()
{
   return {};
}

void foo()
{
   // for(auto e : get_test().items()) - this would cause a new test struct element to be created per each iteration and would invalidate the iterator.
   
   for(auto obj = get_test(); auto e : obj) // test created only once, no iterator invalidation
   {
      std::cout << e << '\n';
   }
}