Reputation: 10126
Accidentally the following code was found:
if (bool result = f()) {
// Do the stuff
}
It was compiled with gcc 4.9.2
and MSVS 2013
.
The following code compiles and prints 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;
}
I thought that this (except syntax) functionality is available only since C++17
.
Do I understand it wrong?
Upvotes: 3
Views: 256
Reputation: 31
Yes. In c++17, we can initialize and then test a condition in if statement.
Example :
if( bool result = foo(); result ) {
std::cout << "True!\n";
} else {
std::cout << "False!\n";
}
It helps us write a cleaner code, if the scope of the variable is just limited to the if statement.
The above will look neat than
bool result = foo();
if( result ) {
std::cout << "True!\n";
} else {
std::cout << "False!\n";
}
Upvotes: 1
Reputation: 69892
c++17 also allows this potentially confusing construct:
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);
}
}
Upvotes: 1
Reputation: 22023
The syntax in c++17 is different:
if(int foo = result(); foo == 1)
The new notation first declares the variable and then makes a test on it. It fixes the issue of assignment and condition test in the same statement that could lead to mistakes.
Upvotes: 4
Reputation: 48958
Do I understand it wrong?
Jup. It was always allowed to have a declaration within the condition of an if statement. What is new in C++17 is that you can have a initializer and a condition:
if (int A = 0; ++A == 1);
// ^^^^^^^^^
// new part
For those asking why this is a useful feature, here's an example that I like from Reddit:
std::map<int, std::string> Map;
// ...
if (auto[it, inserted] = Map.insert(std::pair(10, "10")); inserted)
; // do something with *it.
Upvotes: 14