Here is an example that demonstrates the non-standard use of a variable declared in an if condition.
The type of the variable is int & which can be converted to a boolean value and used in the then and else branches.
#include <string> #include <map> #include <vector> using namespace std; vector<string> names {"john", "john", "jack", "john", "jack"}; names.push_back("bill"); // without this push_back, my g++ generated exe fails :-( map<string, int> ages; int babies = 0; for (const auto & name : names) { if (int & age = ages[name]) { cout << name << " is already " << age++ << " year-old" << endl; } else { cout << name << " was just born as baby #" << ++babies << endl; ++age; } }
exit
john was just born as baby
Unfortunately, a variable in a condition can only be declared with the syntax of declaration =.
This eliminates other possible useful cases of types with an explicit constructor.
For example, the following example using std::ifstream will not compile ...
if (std::ifstream is ("c:/tmp/input1.txt")) {
Edited January 2019 ... now you can imitate what I explained cannot be done ...
This works for movable classes such as ifstream in C ++ 11 and even for non-copyable classes starting with C ++ 17 with copy permission.
Edited May 2019: use auto to ease verbosity
{ if (auto is = std::ifstream ("missing.txt")) { // ok now ! std::cout << "true: " << is.rdbuf(); } else { is.open("main.cpp"); std::cout << "false: " << is.rdbuf(); } } struct NoCpy { int i; int j; NoCpy(int ii = 0, int jj = 0) : i (ii), j (jj) {} NoCpy(NoCpy&) = delete; NoCpy(NoCpy&&) = delete; operator bool() const {return i == j;} friend std::ostream & operator << (std::ostream & os, const NoCpy & x) { return os << "(" << xi << ", " << xj << ")"; } }; { auto x = NoCpy(); // ok compiles // auto y = x; // does not compile if (auto nocpy = NoCpy (7, 8)) { std::cout << "true: " << nocpy << std::endl; } else { std::cout << "false: " << nocpy << std::endl; } }
thierry.bravier Apr 17 '13 at 2:30 a.m. 2013-04-17 02:30
source share