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
}

Leave a Comment