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

时光毁灭记忆、已成空白 提交于 2019-11-27 04:58:57

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;
}

I consider it a good style when used with possibly NULL pointer:

if(CObj* p = GetOptionalValue()) {
   //Do something with p
}

This way whether p is declared, it is a valid pointer. No dangling pointer access danger.

On the other hand at least in VC++ it is the only use supported (i.e. checking whether assignment is true)

I use const as much as possible in these situations. Instead of your example, I would do:

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

So although the scope isn't contained, it doesn't really matter, since the variable can't be altered.

They are fixing this in c++17 :

if (int i = read(socket); i < 0)

where if can have an initializer statement.

see http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0305r0.html

Ferruccio

I've run into a similar problem:

The problem seems to be the parentheses around the int declaration. It should work if you can express the assignment and test without them, i.e.

if (int i = read(socket)) {

should work, but that means the test is != 0, which is not what you want.

While you can use a declaration as a boolean expression, you cannot place a declaration in the middle of an expression. I cannot help thinking that you are mis-reading what Bjarne is saying.

The technique is useful and desirable mostly for control variables of for loops, but in this instance I believe is ill-advised and does not serve clarity. And of course it does not work! ;)

if( <type> <identifier> = <initialiser> ) // valid, but not that useful IMO

if( (<type> <identifier> = <initialiser>) <operator> <operand> )  // not valid

for( <type> <identifier> = <initialiser>; 
     <expression>; 
     <expression> )  // valid and desirable

In your example you have called a function with side effects in a conditional, which IMO is a bad idea regardless of what you might think about declaring the variable there.

White_Pawn

Adding to what RedGlyph and Ferruccio said. May be we can do the following to still declare within a conditional statement to limit its use:

if(int x = read(socket)) //x != 0
{
  if(x < 0) //handle error
  {}
  else //do work
  {}
}
else //x == 0  
{
  return true;
}

To complement the other folks' good answers, you can always limit the scope of the variable by braces:

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

While not directly related to the question, all of the examples put the error handling first. Since there are 3 cases (>0 -> data, ==0 -> connection closed and <0 -> error), that means that the most common case of getting new data requires two tests. Checking for >0 first would cut the expected number of tests by almost half. Unfortunately the "if(int x = read(socket))" approach given by White_Pawn still requires 2 tests for the case of data, but the C++17 proposal could be used to test for >0 first.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!