Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It comes from the history of using integer values as booleans.</p> <p>If <code>x</code> is an <code>int</code>, but I am using it as a boolean as per <code>if(x)...</code> then incrementing will mean that whatever its truth value before the operation, it will have a truth-value of <code>true</code> after it (barring overflow).</p> <p>However, it's impossible to predict the result of <code>--</code> given knowledge only of the truth value of <code>x</code>, as it could result in <code>false</code> (if the integral value is 1) or <code>true</code> (if the integral value is anything else - notably this includes 0 [<code>false</code>] and 2 or more [<code>true</code>]).</p> <p>So as a short-hand <code>++</code> worked, and <code>--</code> didn't.</p> <p><code>++</code> is allowed on bools for compatibility with this, but its use is deprecated in the standard.</p> <hr> <p>This assumes that I <strong>only</strong> use <code>x</code> as an boolean, meaning that overflow can't happen until I've done <code>++</code> often enough to cause an overflow on it's own. Even with char as the type used and <code>CHAR_BITS</code> something low like 5, that's 32 times before this doesn't work any more (that's still argument enough for it being a bad practice, I'm not defending the practice, just explaining why it works) for a 32-bit <code>int</code> we of course would have to use <code>++</code> 2^32 times before this is an issue. With <code>--</code> though it will only result in <code>false</code> if I started with a value of 1 for <code>true</code>, or started with 0 and used <code>++</code> precisely once before.</p> <p>This is different if we start with a value that is just a few below 0. Indeed, in such a case we might want <code>++</code> to result in the <code>false</code> value eventually such as in:</p> <pre><code>int x = -5; while(++x) doSomething(x); </code></pre> <p>However, this example treats <code>x</code> as an <code>int</code> everywhere except the conditional, so it's equivalent to:</p> <pre><code>int x = -5; while(++x != 0) doSomething(x); </code></pre> <p>Which is different to only using <code>x</code> as a boolean.</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