Defining a variable in the condition part of an if-statement?

Kiril Kirov picture Kiril Kirov · Sep 29, 2012 · Viewed 15.7k times · Source

I was just shocked, that this is allowed:

if( int* x = new int( 20 ) )
{
    std::cout << *x << "!\n";
    // delete x;
}
else
{
    std::cout << *x << "!!!\n";
    // delete x;
}
// std:cout << *x; // error - x is not defined in this scope

So, is this allowed by the standard or it's just a compiler extension?


P.S. As there were several comments about this - please ignore that this example is "bad" or dangerous. I know what. This is just the first thing, that came to my mind, as an example.

Answer

pb2q picture pb2q · Sep 29, 2012

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
}