Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: minor fix

...

Wiki Markup
Another tool for avoiding integer overflow is to use only half the range of signed integers.  For example, when using an {{int}}, use only the range \[{{INT_MIN}}/2, {{INT_MAX}}/2\].  This has been a trick of the trade in Fortran for some time, and now that optimizing C compilers are becoming more sophisticated, it can be valuable in C.

Wiki Markup
Consider subtraction. If the user types the expression {{a - b}} where both a and b are in the range {{\[INT_MIN/2, INT_MAX/2\]}}, then the  answer will be in the range {{(INT_MIN, INT_MAX]}} for a typical two's  complement machine.

Now, if the user types a < b there is often an implicit subtraction happening. On a machine without condition codes, the compiler may simply issue a subtract instruction and check whether the result is negative. This is allowed, since the compiler is allowed to assume there is no overflow. If all explicitly user-generated values are kept in the range [INT_MIN/2, INT_MAX/2, then comparisons will always work even if the compiler performs this optimization on such hardware.

...