加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

if语句中的初始化是否存在于C 17之前?

发布时间:2020-12-16 10:49:47 所属栏目:百科 来源:网络整理
导读:无意中发现了以下代码: if (bool result = f()) { // Do the stuff} 它是用gcc 4.9.2和MSVS 2013编译的. 以下代码编译并打印False!: #include iostreambool foo() { return false;}void bar() { if (bool result = foo()) { std::cout "True!n"; } else
无意中发现了以下代码:

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;
}

我认为这个(语法除外)功能仅在C17之后才可用.

我明白错了吗?

解决方法

Do I understand it wrong?

杰普.始终允许在if语句的条件下声明. C 17的新功能是你可以有一个初始化器和条件:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读