Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Let's attempt to also modify <code>i</code> when we increment <code>j</code>:</p> <pre><code>int j = 0; for (int i = 0 ; i &lt; 100 ; ++i) if (i % 2 == 0) j++; i++; </code></pre> <p>Oh no! Coming from Python, this looks ok, but in fact it isn't, as it's equivalent to:</p> <pre><code>int j = 0; for (int i = 0 ; i &lt; 100 ; ++i) if (i % 2 == 0) j++; i++; </code></pre> <p>Of course, this is a silly mistake, but one that even an experienced programmer could make.</p> <p><strong>Another very good reason</strong> is pointed out in <a href="https://stackoverflow.com/a/12193223/673730">ta.speot.is's answer</a>.</p> <p><strong>A third</strong> one I can think of is nested <code>if</code>'s:</p> <pre><code>if (cond1) if (cond2) doSomething(); </code></pre> <p>Now, assume you now want to <code>doSomethingElse()</code> when <code>cond1</code> is not met (new feature). So:</p> <pre><code>if (cond1) if (cond2) doSomething(); else doSomethingElse(); </code></pre> <p>which is obviously wrong, since the <code>else</code> associates with the inner <code>if</code>.</p> <hr> <p>Edit: Since this is getting some attention, I'll clarify my view. The question I was answering is:</p> <blockquote> <p>What's the benefit of using the 1st version?</p> </blockquote> <p>Which I have described. There are some benefits. But, IMO, "always" rules don't always apply. So I don't wholly support</p> <blockquote> <p>Always use a { } block - even for a single line // not OK, why ???</p> </blockquote> <p>I'm not saying <em>always</em> use a <code>{}</code> block. If it's a simple enough condition &amp; behavior, don't. If you suspect someone might come in later &amp; change your code to add functionality, do.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload