作者:挠挠扣扣笑嘻嘻 | 来源:互联网 | 2022-12-02 18:44
无意中发现了以下代码:
if (bool result = f()) {
// Do the stuff
}
它是用gcc 4.9.2
和编译的MSVS 2013
.
以下代码编译并打印False!
:
#include
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
.
我明白错了吗?
1> Rakete1111..:
我明白错了吗?
杰普.始终允许在if语句的条件下声明.C++ 17的新功能是你可以有一个初始化器和条件:
if (int A = 0; ++A == 1);
// ^^^^^^^^^
// new part
对于那些问为什么这是一个有用功能的人来说,这是我喜欢Reddit的一个例子:
std::map Map;
// ...
if (auto[it, inserted] = Map.insert(std::pair(10, "10")); inserted)
; // do something with *it.
@MatthewFisher:`if(int x = foo(); x> 42)`你可以在整个条件中使用`foo()`的结果(请注意,这也可以在任何链接的`else`中使用!)_并且它可以保存你围绕`if`只为&#39;x`创建一个全新的范围,_或_不打扰和"泄漏"`x`到周围环境.而且它在语法上更优雅.阅读http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0305r0.html; 它非常引人注目.
@Bathsheba你的机器是生产的.
@MatthewFisher"A"的范围仅限于"if"体.没有新功能,你会怎么做?
@MatthewFisher 1.保持可变范围尽可能小; 2.错误传播