Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pro/con: Initializing a variable in a conditional statement

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.

like image 243
steffenj Avatar asked Sep 25 '08 22:09

steffenj


People also ask

Can we initialize a variable in if condition?

C++17 If statement with initializer Now it is possible to provide initial condition within if statement itself. This new syntax is called "if statement with initializer".

What are the benefits of initializing variables?

Initializing a variable as Telastyn pointed out can prevent bugs. If the variable is a reference type, initializing it can prevent null reference errors down the line. A variable of any type that has a non null default will take up some memory to store the default value.

Should variables be initialized?

Generally, all variables should be explicitly initialized in their declaration. The descriptive comment is optional. In most cases, variable names are descriptive enough to indicate the use of the variable.

What does initializing a variable mean?

To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.


1 Answers

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())
    {
    }
}
like image 181
Wesley Tarle Avatar answered Sep 28 '22 08:09

Wesley Tarle