if (init; condition) {}
(Ref: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p030...). It just seems like clutter. I generally prefer when languages discourage side effects in a branch condition.
if (init; condition) {}
(Ref: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p030...). It just seems like clutter. I generally prefer when languages discourage side effects in a branch condition.
{
std::unique_ptr<T> x = foo();
if(x->something()) {
// use x
}
}
// x out of scope, destructed
becomes if(auto x = foo(); x->something()) {
// use x
}
// x out of scope, destructed
It's makes it easier to read the lifetime of x (an important thing you have to manually keep an eye on in C++ in many cases), and to determine what is in scope outside of the if statement. It's analogous to for-loops vs. doing loops "manually" with while. You're just used to for-loops by this point (if you don't like for loops then ok :).)C# is also getting (has got?) this feature.
It does improve readability. If you've ever had to have a series of conditionals in their own braces to keep the init variable in its own scope, then you have a use for this. The alternative might be having foo1, foo2, foo3… all in the same scope, and it's too easy to use the wrong one. This keeps things specifically constrained to the scope in which they are used, which improves safety and correctness, and I think also readability once you adapt to it.
Yes, it could be abused, but I don't think that's a reason not to use it for its intended purpose.
And agreed that people mess for loops up, and range based loops are better. My point was only related to the syntactic precedent for coupling an initialiser and conditional in a statement.
In most languages, in most cases, scopes within a function are used to enhance readability rather than to specify program logic, so a feature like this would add more complexity than it removes.
if (std::vector<int> v = f(); !v.empty()) { // Use v }
without requiring an extra compound statement to limit the scope and lifetime of v.