Pro/con: Initializing a variable in a conditional statement
- by steffenj
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.
Question borrowed from here, similar topic but PHP.