[英]Initialization in if statement existed before C++17?
無意中發現了以下代碼:
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
可用。
我明白錯了嗎?
我明白錯了嗎?
傑普。 始終允許在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.
c ++ 17中的語法不同:
if(int foo = result(); foo == 1)
新的表示法首先聲明變量,然后對其進行測試。 它修復了可能導致錯誤的同一語句中的賦值和條件測試問題。
是。 在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";
}
c ++ 17也允許這個可能令人困惑的結構:
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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.