If Else statement indentation important or not? (C++)

  • A+
Category:Languages

Does the indentation in an if else statement have any bearing on the execution of the code or is it just something to do for cleaner codes?

example from the book Accelerated C++ written by Andrew Koening:

while(c != cols){     if(r == pad + 1 && c == pad + 1){       cout << greet;       c+=greet.size();     } else {        if(r == 0 || r == rows - 1 || c == 0 || c == cols - 1)         cout << "*";        else         cout << " ";         ++c;       }    } 

The prefix increment of c is executed regardless of whether r=0 or not but I dont understand why.

If the if statement turns true an asterisk is printed. IF not a blank space is printed and c is incremented. Thats how I am reading it but c gets incremented regardless of what the values of r or c are.

This is what it says in the book but theres no explanation I could find:

Notice how the different indentation of ++c; draws attention to the fact that it is executed regardless of whether we are in the border.


Whitespace does not affect C++ runtime behavior. (Unlike certain other languages, like Python).

I should mention that in your else block, you do not use braces. So, only the first statement (cout << " ";) will be part of the else clause. The subsequent ++c; will execute regardless of the value of r and c.

Note that this last point is subjective, so take it with a grain of salt... As you can see, when braces are omitted from if ... else ... blocks, there is potential for confusion. Some would argue that it leads to more concise code, but many (including myself) would argue that you should always use braces. This is especially important when you work on a large team because code tends to grow over time. I've seen many cases in production code where an if statement was missing the braces and someone added a second line to the if clause without remembering to add braces. This didn't work as expected and caused wasted time debugging fails, just because the braces were omitted.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: