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

后端 未结 9 1440

In Stroustrup\'s The C++ Programming Language: Special Edition (3rd Ed), Stroustrup writes that the declaration and initialization of variables in the conditionals

9条回答
  •  醉酒成梦
    2020-11-30 11:21

    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(   =  ) // valid, but not that useful IMO
    
    if( (  = )   )  // not valid
    
    for(   = ; 
         ; 
          )  // 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.

提交回复
热议问题