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

后端 未结 9 1431

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:33

    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)

提交回复
热议问题