Pro/con: Initializing a variable in a conditional statement

前端 未结 12 1279
Happy的楠姐
Happy的楠姐 2021-01-01 18:24

In C++ you can initialize a variable in an if statement, like so:

if (CThing* pThing = GetThing())
{
}

Why would one consider this bad or g

12条回答
  •  旧巷少年郎
    2021-01-01 19:15

    The important thing is that a declaration in C++ is not an expression.

    bool a = (CThing* pThing = GetThing()); // not legit!!
    

    You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.

    if(A *a = new A)
    {
        // this is legit and a is scoped here
    }
    

    How can we know whether a is defined between one term and another in an expression?

    if((A *a = new A) && a->test())
    {
        // was a really declared before a->test?
    }
    

    Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:

    if (CThing* pThing = GetThing())
    {
        if(pThing->IsReallySomeThing())
        {
        }
    }
    

提交回复
热议问题