In Stroustrup\'s The C++ Programming Language: Special Edition (3rd Ed), Stroustrup writes that the declaration and initialization of variables in the conditionals
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)
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
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.