Pro/con: Initializing a variable in a conditional statement
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())
{
}
}
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).
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
if (CThing* pThing = GetThing())
It is bad style, because inside the if
you are not providing a boolean expression. You are providing a CThing*
.
CThing* pThing = GetThing();
if (pThing != NULL)
This is good style.