Pro/con: Initializing a variable in a conditional statement

Posted by steffenj on Stack Overflow See other posts from Stack Overflow or by steffenj
Published on 2008-09-25T22:18:08Z Indexed on 2010/04/04 5:23 UTC
Read the original article Hit count: 236

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about c++

Related posts about coding-style