what is the usage?
Declaration inside if
/for
/while
allows to reduce scope of the variable.
so, instead of
int y = somevalue();
if (y) {// y != 0
// ...
}
// y still usable :/
or
{ // extra block :/
int y = somevalue();
if (y) {// y != 0
// ...
}
}
// y no longer usable :)
you might directly do:
if (int y = somevalue()) // y != 0
// ...
}
// y no longer usable :)
with syntax which might indeed surprise.
For more controversial:
int y;
// ...
if (y = somevalue()) // y != 0
// ...
}
// y still usable :)
it is allowed as that assignation is an expression convertible to bool (value of y = x
is y
(which has been assigned to x
)).
it is more controversial as error prone as unclear if =
or ==
is expected.
some convention use extra parents to more clearly express assignation
if ((y = somevalue())) // really = intended, not ==
// ...
}
when someone should do this in his project?
For existing projects, try to use existing convention.
For new project, you have to do the trade of:
scope versus syntax not shared with other language which might be surprising
and when conditions like these give result true?
when given expression convert to true, so non zero integral, non null pointer.
c++17 introduces another syntax to allow to split declaration and condition for if
/while
. (for
already allow that split)
if (int y = somevalue(); y != 42) // y != 42
// ...
}
// y no longer usable :)