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

前端 未结 5 457
夕颜
夕颜 2020-12-13 12:14

I was just shocked, that this is allowed:

if( int* x = new int( 20 ) )
{
    std::cout << *x << \"!\\n\";
    // delete x;
}
else
{
    std::cout         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 12:23

    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
    }
    

提交回复
热议问题