When was the ability to declare a variable in the if statement introduced in C++?

Viewed 80

In C++, we can declare variables directly in the if statement and its value is used as the condition, e.g.

if (SubClass *subObject = dynamic_cast<SubClass *>(baseObject)) {
    // ...
}

For some reason, I always assumed that this was a "relatively" new feature, introduced in C++11 at the earliest, but when I tried to confirm this, I found no information about this, only that C++17 expands the syntax even further. When I tried compiling a minimal example with -std=c++98, it worked. So has this been a feature of C++ from the beginning?

1 Answers

The first formal C++ Standard was ISO/IEC 14882:1998 (a.k.a. C++98). In this 'draft' version of that, the declaration of a variable inside an if statement is explicitly mentioned:

6.4 Selection statements       [stmt.select]



3     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. If the name is re-declared in the outermost block of a substatement controlled by the condition, the declaration that re-declares the name is ill-formed. [Example:

if (int x = f()) {
            int x; // ill-formed, redeclaration of x
} else { 
            int x; // ill-formed, redeclaration of x
}

—end example]

So, in terms of formal Standards: Yes, it's "been there since the beginning."

Related