Defining a variable in the condition part of an if-statement?
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
}
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.