代码之家  ›  专栏  ›  技术社区  ›  Alex

IF语句在C++ 17之前存在初始化?

  •  3
  • Alex  · 技术社区  · 7 年前

    if (bool result = f()) {
        // Do the stuff
    }
    

    它是用 gcc 4.9.2 MSVS 2013 .

    下面的代码编译并打印 False! :

    #include <iostream>
    
    bool foo() {
        return false;
    }
    
    void bar() {
        if (bool result = foo()) {
            std::cout << "True!\n";
        } else {
            std::cout << "False!\n";
        }
    }
    
    int main()
    {
        bar();
    
        return 0;
    }
    

    C++17 .

    我理解错了吗?

    4 回复  |  直到 7 年前
        1
  •  14
  •   Rakete1111    7 年前

    朱普。它总是被允许在 条件

    if (int A = 0; ++A == 1);
    //  ^^^^^^^^^
    //  new part
    

    对于那些问为什么这是一个有用的特性的人,下面是我喜欢的Reddit的一个例子:

    std::map<int, std::string> Map;
    // ...
    
    if (auto[it, inserted] = Map.insert(std::pair(10, "10")); inserted)
        ; // do something with *it.
    
        2
  •  4
  •   Kuba hasn't forgotten Monica    7 年前

    c++17中的语法不同:

    if(int foo = result(); foo == 1)
    

    新的表示法首先声明变量,然后对其进行测试。它修复了同一语句中可能导致错误的赋值和条件测试问题。

        3
  •  1
  •   Richard Hodges    7 年前

    int bar();
    bool query();
    void foo(int, bool);
    
    int main()
    {
        if (int x = bar() ; bool y = query())
        {
            foo(x, y);
        }
        else
        {
            foo(x * 2, y);
        }
    }
    
        4
  •  1
  •   Rafael    7 年前

    对。在c++17中,我们可以在if语句中初始化并测试一个条件。

     if( bool result = foo(); result ) {
        std::cout << "True!\n";
     } else {
        std::cout << "False!\n";
     }
    

    如果变量的作用域仅限于if语句,它可以帮助我们编写更干净的代码。

     bool result = foo();
     if( result ) {
        std::cout << "True!\n";
     } else {
        std::cout << "False!\n";
     }