It limits the scope of length to the if alone. So you get the same benefits we originally got when we were allowed to write
for(int i = 0; i < ... ; ++i) {
// ...
}
Instead of the variable leaking
int i;
for(i = 0; i < ... ; ++i) {
// ...
}
Short lived variables are better for several reasons. But to name a couple:
-
The shorter something lives, the less things you need to keep in mind when reading unrelated lines of code. If
idoesn’t exist outside the loop orifstatement, then we don’t need to mind its value outside of them. Nor do we need to worry its value will interact with other parts of the program that are outside of its intended scope (which may happen ifiabove is reused in another loop). It makes code easier to follow and reason about. -
If the variable holds a resource, then that resource is now held for the shortest period possible. And this is without extraneous curly braces. It’s also made clear the resource is related to the
ifalone. Consider this as a motivating exampleif(std::lock_guard _(mtx); guarded_thing.is_ready()) { }
If your colleagues aren’t aware of the feature, teach them! Appeasing programmers who don’t wish to learn is a poor excuse to avoid features.