Declaring and initializing a variable in a Conditional or Control statement in C++

It is allowed to declare a variable in the control part of a nested block, but in the case of if and while, the variable must be initialized to a numeric or boolean value that will be interpreted as the condition. It cannot be included in a more complex expression!

In the particular case you show, it doesn’t seem you can find a way to comply unfortunately.

I personally think it’s good practice to keep the local variables as close as possible to their actual lifetime in the code, even if that sounds shocking when you switch from C to C++ or from Pascal to C++ – we were used to see all the variables at one place. With some habit, you find it more readable, and you don’t have to look elsewhere to find the declaration. Moreover, you know that it is not used before that point.


Edit:

That being said, I don’t find it a good practice to mix too much in a single statement, and I think it’s a shared opinion. If you affect a value to a variable, then use it in another expression, the code will be more readable and less confusing by separating both parts.

So rather than using this:

int i;
if((i = read(socket)) < 0) {
    // handle error
}
else if(i > 0) {
    // handle input
}
else {
    return true;
}

I would prefer that:

int i = read(socket);
if(i < 0) {
    // handle error
}
else if(i > 0) {
    // handle input
}
else {
    return true;
}

Leave a Comment