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.
This is allowed by the specification, since C++98.
From Section 6.4 “Selection statements”:
The following example is from the same section: