In C++ you can initialize a variable in an if statement, like so:
if (CThing* pThing = GetThing())
{
}
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.
Best Solution
The important thing is that a declaration in C++ is not an expression.
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.
How can we know whether a is defined between one term and another in an expression?
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit: