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

后端 未结 9 1430

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)

    0 讨论(0)
  • 2020-11-30 11:40

    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

    0 讨论(0)
  • 2020-11-30 11:40

    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.

    0 讨论(0)
提交回复
热议问题