Integer overflow: Difference between revisions
Content added Content deleted
(Added description of Nim overflow detection.) |
|||
Line 1,512: | Line 1,512: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
⚫ | |||
In Nim, overflow during operations on signed integers is detected and raises an exception. Starting from version 1.4, overflows are defects. For now, by default, defects can be caught but in future versions this may and probably would change. Using compile option <code>--panics:on</code> makes defects impossible to catch. |
|||
In the INT64 case the Nim program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>. |
|||
Catching an overflow (when --panics is off) is done this way: |
|||
<lang Nim>try: |
|||
var x: int32 = -2147483647 |
|||
x = -(x - 1) # Raise overflow. |
|||
echo x |
|||
except OverflowDefect: |
|||
echo "Overflow detected"</lang> |
|||
It is possible to tell the compiler to not generate code to detect overflows by using pragmas “push” and “pop”: |
|||
<lang Nim>{.push overflowChecks: off.} |
|||
try: |
|||
var x: int32 = -2147483647 |
|||
x = -(x - 1) |
|||
echo x # -2147483648 — Wrong result as 2147483648 doesn't fit in an int32. |
|||
except OverflowDefect: |
|||
echo "Overflow detected" # Not executed. |
|||
{.pop.}</lang> |
|||
It is also possible to suppress all overflow checks by using compile option <code>--overflowChecks:off</code>. Also, compiling with option <code>-d:danger</code> suppress these checks and several others. |
|||
For unsigned integers, Nim doesn’t check for overflow but uses modular arithmetic. |
|||
===Program to check behavior when overflow is not detected=== |
|||
This program presents the behavior when overflow checks are suppressed. Remember that for signed integers, this is not the normal behavior. |
|||
⚫ | |||
<lang Nim>import macros, strutils |
<lang Nim>import macros, strutils |
||
{.push overflowChecks: off.} |
|||
macro toIntVal(s: static[string]): untyped = |
macro toIntVal(s: static[string]): untyped = |
||
Line 1,609: | Line 1,638: | ||
main() |
main() |
||
</lang> |
{.pop.}</lang> |
||
{{out}} |
{{out}} |
||
<pre>-- INT32 -- |
<pre>-- INT32 -- |