Initializing variables in an “if” statement

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:

  1. The shorter something lives, the less things you need to keep in mind when reading unrelated lines of code. If i doesn’t exist outside the loop or if statement, 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 if i above is reused in another loop). It makes code easier to follow and reason about.

  2. 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 if alone. Consider this as a motivating example

    if(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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)