C++17 からの if 条件式内での宣言 ― 2021年06月05日 11時44分45秒
関数を呼んだ後に戻り値を点検したり、エラーだった戻り値を if 条件式の中で変数が有効なので、戻り値を点検して処理する用途で使いやすい。変数の寿命を限定したり、戻り値を const で受け取りやすくなる。
C++17 以前でコンパイルすると、clang だとこのような警告が出る。
% cat if.cpp
#include <iostream>
int main()
{
if( auto i = 1 + 2; i > 2 )
std::cout << "i is greater than 2: " << i << std::endl
;
}
% c++ -std=c++13 if.cpp
if.cpp:5:9: warning: 'if' initialization statements are a C++17 extension [-Wc++17-extensions]
if( auto i = 1 + 2; i > 2 )
^
1 warning generated.
% c++ -std=c++17 if.cpp
% ./a.out
i is greater than 2: 3
最近のコメント