Defining a variable in the condition part of an if-statement?
Definition of a variable in the conditional part of a while
, if
, and switch
statement are standard. The relevant clause is 6.4 [stmt.select] paragraph 1 which defines the syntax for the condition.
BTW, your use is pointless: if new
fails it throws a std::bad_alloc
exception.
This is allowed by the specification, since C++98.
From Section 6.4 "Selection statements":
A name introduced by a declaration in a condition (either introduced by the type-specifier-seq or the declarator of the condition) is in scope from its point of declaration until the end of the substatements controlled by the condition.
The following example is from the same section:
if (int x = f()) {
int x; // ill-formed, redeclaration of x
}
else {
int x; // ill-formed, redeclaration of x
}
It is standard, even in the old C++ 98 version of the language:
Not really an answer (but comments are not well suited to code samples), more a reason why it's incredibly handy:
if (int* x = f()) {
std::cout << *x << "\n";
}
Whenever an API returns an "option" type (which also happens to have a boolean conversion available), this type of construct can be leveraged so that the variable is only accessible within a context where it is sensible to use its value. It's a really powerful idiom.