Pro/con: Initializing a variable in a conditional statement

前端 未结 12 1219
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 18:59

    I see that as kind of dangerous. The code below is much safer and the enclosing braces will still limit the scope of pThing in the way you want.

    I'm assuming GetThing() sometimes returns NULL which is why I put that funny clause in the if() statement. It prevents IsReallySomething() being called on a NULL pointer.

    {
        CThing *pThing = GetThing();
        if(pThing ? pThing->IsReallySomeThing() : false)
        {
        // Do whatever
        }
    }
    
    0 讨论(0)
  • 2021-01-01 19:00

    also notice that if you're writing C++ code you want to make the compiler warning about "=" in a conditional statement (that isn't part of a declaration) an error.

    0 讨论(0)
  • 2021-01-01 19:03

    About the advantages:

    It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.

    Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).

    0 讨论(0)
  • 2021-01-01 19:03

    You can have initialization statements inside if and switch since C++17.

    Your code would now be:

    if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())
    {
        // use pThing here
    }
    // pThing is out of scope here
    
    0 讨论(0)
  • 2021-01-01 19:09

    It's acceptable and good coding practice. However, people who don't come from a low-level coding background would probably disagree.

    0 讨论(0)
  • 2021-01-01 19:11

    You can also enclose the assignment in an extra set of ( ) to prevent the warning message.

    0 讨论(0)
提交回复
热议问题