Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was just shocked, that this is allowed:

if( int* x = new int( 20 ) )
{
    std::cout << *x << "!
";
    // delete x;
}
else
{
    std::cout << *x << "!!!
";
    // 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
153 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...