Integer overflow: Difference between revisions

Content added Content deleted
No edit summary
(Added Wren)
Line 2,352: Line 2,352:
<pre>
<pre>
Arithmetic operation resulted in an overflow.
Arithmetic operation resulted in an overflow.
</pre>

=={{header|Wren}}==
Wren only has a single numeric type, Num, instances of which are represented by 8 byte double precision floating point values.

This means that '''safe''' integer arithmetic is only possible up to (plus or minus) 2^53 - 1 (9,007,199,254,740,991) and, whilst there is no integer overflow as such, you are likely to get inaccurate results, without warning, if calculations exceed this limit. Worse still, this inaccuracy is difficult to observe in practice as the standard ''System.print'' method
switches to scientific notation when printing integers with more than 14 digits.

However, within this overall framework, Wren also has an unsigned 32-bit integer sub-system when dealing with bitwise operations. All values are converted internally to such integers before the corresponding C bitwise operation is performed (Wren's VM is written in C) and can therefore overflow without warning. Fortunately, we can easily observe these effects by performing the operations required by the task and then (for example) right shifting them by 0 places.
<lang ecmascript>var exprs = [-4294967295, 3000000000 + 3000000000, 2147483647 - 4294967295, 65537 * 65537]

for (expr in exprs) System.print(expr >> 0)</lang>
System.print("Unsigned 32-bit:")
{{out}}
Results agree with those for the corresponding C entry above.
<pre>
Unsigned 32-bit:
1
1705032704
2147483648
131073
</pre>
</pre>