Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>C cares nothing about your algorithm, nor does it know whether your variables will underflow or not, nor does it know if the underflow is intentional or accidental. Under-/overflows for unsigned integers is well-defined behavior, so in this case the compiler will happily do what you tell it to: create an underflow.</p> <hr> <p>Some details:</p> <pre><code>unsigned int secondsLeft = (currentTickSeconds - prevTickSeconds ) ? currentTickSeconds - prevTickSeconds : 60 - prevTickSeconds + currentTickSeconds; </code></pre> <p>If we replace all variables in this expression with their corresponding types, we get:</p> <pre><code>unsigned int = (unsigned int - unsigned int) ? unsigned int - unsigned int : int - unsigned int + unsigned int; </code></pre> <p>All C cares about is its implicit type promotion rules. There are two such rules in this expression: regular balancing (<em>the usual arithmetic conversions</em>) and a special balancing rule for the ?: operator.</p> <p>The balancing rules state that if two integers of the same size are operands of an expression, and one of them is unsigned, the signed operand will get converted to an unsigned one.</p> <pre><code>unsigned int = (unsigned int - unsigned int) ? // no conversion needed unsigned int - unsigned int : // no conversion needed (int - unsigned int) // convert the int to unsigned int + unsigned int; // we get unsigned + unsigned, no conversion needed </code></pre> <p>And then the result is stored in an unsigned int.</p> <p>There is however a special (weird) rule in C, related to the conditional operator ?:. The 2nd operand and and the 3rd operand are balanced as if they were operators of the same expression. So if you have this case:</p> <pre><code>1 ? (signed int)x : (unsigned int)y; </code></pre> <p>then the result will always be unsigned int. This is because x and y are treated as if they were part of the same operation, even though y is never used in the code. This can create subtle bugs and it is reason enough to avoid the ?: operator entirely, in my opinion.</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