0

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 code?

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 don’t understand why.

If the if statement turns true, an asterisk is printed. If not, a blank space is printed and c is incremented. That’s 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 there isn’t any 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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Karl S.
  • 129
  • 2
  • 6
  • 2
    Put another way, you could put everything except preprocessor directives on the same line and it would still compile, producing the same behavior. – François Andrieux May 24 '18 at 18:14
  • 3
    Is that really how `++c;` is indented in the book? I'll bet it actually lines up with `if` and `else`, not with `cout`. – Barmar May 24 '18 at 18:15
  • Related: https://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar May 24 '18 at 18:17
  • That should be what it means by "the different indentation of ++c" – Barmar May 24 '18 at 18:18
  • Indentation only serves to aid or deceive the reader. The code in your example deceives. – Drew Dormann May 24 '18 at 18:22
  • 3
    My bikeshedding rule of thumb is to always use curly braces `{...}` for the body of an `if`/`else`. But C++ does not require them for a single statement body. That's just me; other people have strong opinions in favor never using optional curly braces. Indentation is another perennial bikeshedding topic. There are no right answers, only strong opinions. These kinds of topics are best discussed over good beer. – Eljay May 24 '18 at 18:24
  • Um... let python be strong with author of that code... No, indentation doesn't affect it and if code was written like that , I assume: a) that was typographic mistake , or b) author was pulling reader's leg. – Swift - Friday Pie May 24 '18 at 18:37
  • @Eljay excellent plan, but first we must agree on what constitutes good beer. – user4581301 May 24 '18 at 18:45
  • 2
    Did the indentation of that code get mangled in translation? – Paul Sanders May 24 '18 at 18:46
  • 2
    @user4581301 Possibly, but not according to the text in the yellow box. Anyway, it's hideous, the answer to the _title_ of the question is yes, but the answer to the first line of the question is no. – Paul Sanders May 24 '18 at 18:51
  • @user4581301• good beer is the beer I like. Bad beer is the beer that is indented wrong or puts the curly braces in the wrong spot. – Eljay May 25 '18 at 00:51

4 Answers4

15

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.

Tim Johns
  • 540
  • 3
  • 13
  • 1
    Your second paragraph is saying what the quoted part of the book is also explaining. – Barmar May 24 '18 at 18:16
  • 2
    @Barmar Right, but that's what the OP is confused about. So hopefully my re-wording will help. – Tim Johns May 24 '18 at 18:17
  • 1
    *"Whitespace does not affect C++"*. pedantically, omitting space may change semantic/validity of some code `C>` in C++03, `a++b` (vs `a + +b`) `operator ""` with MACRO concatenation (`#define M(S) "prefix"S`), ...but indeed if it `0` versus `1+` spaces. – Jarod42 May 24 '18 at 21:29
2

Both C and C++ are not affected by white space in their interpretation of the code. That does not mean the programmer should not care about its misuse.

The best way to illustrate what the above code actually represents is to explicitly define all of the inferred braces as below. Note that the if statement that had no braces only has one line of code affected by the 'if then' or 'else' clause.

This is one of the reasons that people try to insist on 'good coding practices' to ensure that other people are able to clearly interpret the flow and intent of the programmer.

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;
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
webmite
  • 575
  • 3
  • 6
0

In C++ the length of indentation does not affect the interpretation of the statements. Sometimes whitespace is needed to separate characters, e.g., in int a. Other times it is not needed, e.g. in a=b+c;.

The if statement is defined that after the condition if(condition) can only be one statement.

If we want more statements we have to group them with braces {...}

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
-1

Unlike Python, C++ does not care about indentation.

But your else applies only on the first line. To apply to a block, it should be within { }

else
{
   cout << " ";
   ++c;
}

Indentation is not your problem here.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
philippe lhardy
  • 3,096
  • 29
  • 36