Integer overflow: Difference between revisions

New post showing additional methods introduced in Java 8, in addition to an existing post which was retained.
m (→‎{{header|Perl}}: added </lang> to match the <lang c> [??])
(New post showing additional methods introduced in Java 8, in addition to an existing post which was retained.)
 
(13 intermediate revisions by 10 users not shown)
Line 116:
<br>
If you mask, you can test it in your program:
<langsyntaxhighlight lang="360asm"> L 2,=F'2147483647' 2**31-1
L 3,=F'1' 1
AR 2,3 add register3 to register2
BO OVERFLOW branch on overflow
....
OVERFLOW EQU *</langsyntaxhighlight>
On the other hand,
you will have the S0C8 system abend code : '''fixed point overflow exception'''
with the same program, if you unmask bit 20 by:
<langsyntaxhighlight lang="360asm"> IPM 1 Insert Program Mask
O 1,BITFPO unmask Fixed Overflow
SPM 1 Set Program Mask
...
DS 0F alignment
BITFPO DC BL1'00001000' bit20=1 [start at 16]</langsyntaxhighlight>
=={{header|6502 Assembly}}==
===8-Bit Overflow===
Signed overflow (crossing the 7F-80 boundary) is detected by the CPU's overflow flag <code>V</code>.
 
Unsigned overflow from 255 to 0 is detected by the CPU's carry flag <code>C</code>.
Unsigned overflow (crossing the FF-00 boundary) is detected by the CPU's carry flag <code>C</code>.
 
The following instructions allow for branching based on the state of these flags:
Line 144 ⟶ 145:
These flags will automatically be set or cleared depending on the results of a calculation that can affect them.
 
<langsyntaxhighlight lang="6502asm">LDA #$7F
CLC
ADC #$01
BVS ErrorHandler ;this branch will always be taken.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="6502asm">LDA #$FF
CLC
ADC #$01
BCS ErrorHandler ;this branch will always be taken.</langsyntaxhighlight>
 
Keep in mind that not all instructions affect the flags in the same way. The only arithmetic instructions that affect the overflow flag are <code>ADC</code> and <code>SBC</code>. Therefore, signed overflow can be "missed" by the CPU very easily if it occurs in other ways:
 
<langsyntaxhighlight lang="6502asm">LDX #$7F
INX ;although X went from $7F to $80, INX does not affect the overflow flag!
BVS ErrorHandler ;whether this branch is taken has NOTHING to do with the INX instruction.</langsyntaxhighlight>
 
<langsyntaxhighlight lang="6502asm">LDA #%01000000
ORA #%10000000 ;accumulator crossed from below $7F to above $80, but ORA doesn't affect the overflow flag.
BVS ErrorHandler ;whether this branch is taken has NOTHING to do with the ORA instruction.</langsyntaxhighlight>
 
 
The same is true for unsigned overflow, but less so since the zero flag can be used as a substitute in these cases.
<langsyntaxhighlight lang="6502asm">LDX #$FF
INX ;the carry flag is not affected by this unsigned overflow, but the zero flag will be set
; so we can detect overflow that way instead!
BEQ OverflowOccurred ;notice that we used BEQ here and not BCS.</langsyntaxhighlight>
 
By default, the CPU will continue with the wrong result, unless you specifically program a branch based on overflow after the calculation. This is because on a hardware level the CPU has no knowledge of whether you intend your data to be signed or unsigned (this is still true even on modern computers).
Line 176 ⟶ 177:
Unlike in [[Z80 Assembly]], the 6502 has no 16-bit registers or built-in 16-bit arithmetic instructions. It ''can'' perform 16-bit or higher addition and subtraction, by separating the number into 8-bit pieces and operating on them separately. Unfortunately, this means that the 6502's flags cannot look at the number as a whole; only the individual bytes. As a result, the CPU will detect "overflow" when any of the bytes cross the $7F-$80 boundary, regardless of whether the byte is the most significant byte or not. This is another reason why the ability to selectively ignore overflow is handy, as it only counts as signed overflow when the most significant byte crosses the $7F-$80 boundary.
 
<langsyntaxhighlight lang="6502asm">;adding two 16-bit signed numbers, the first is stored at $10 and $11, the second at $12 and $13.
;The result will be stored at $14 and $15.
 
Line 191 ⟶ 192:
ADC $13 ;high byte of second operand
STA $15 ;high byte of result
BVS HandleOverflow ;only check for overflow when adding the most significant bytes.</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Overflow happens when certain arithmetic operations result in the most significant byte of the register crossing over from 0x7F to 0x80. (Which byte of the 32-bit register is treated as "most significant" depends on the data size of the last instruction. See the example below)
 
<langsyntaxhighlight lang="68000devpac">MOVE.W D0,#0000117F
ADD.W #1,D0 ;DOESN'T SET THE OVERFLOW FLAG, SINCE AT WORD LENGTH WE DIDN'T CROSS FROM 7FFF TO 8000
 
SUB.B #1,D0 ;WILL SET THE OVERFLOW FLAG SINCE AT BYTE LENGTH WE CROSSED FROM 80 TO 7F</langsyntaxhighlight>
 
Like the 6502, the 68000 will continue with the wrong result unless you tell it to stop. As with the majority of computer architectures, whether a value is "signed" or "unsigned" is not actually a property of the value itself, but of the comparators used to evaluate it. Otherwise even unsigned arithmetic would produce overflow errors! There are a few options for handling overflow errors:
Line 209 ⟶ 210:
In Ada, both predefined and user-defined integer types are in a given range, between Type'First and Type'Last, inclusive. The range of predefined types is implementation specific. When the result of a computation is out of the type's range, the program <b>does not continue with a wrong result, but</b> instead <b>raises an exception</b>.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Overflow is
Line 259 ⟶ 260:
A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR
end loop;
end Overflow;</langsyntaxhighlight>
 
{{out}}
Line 290 ⟶ 291:
 
Other implementations are at liberty to take any action they wish, including to continue silently with a "wrong" result or to throw a catchable exception (though the latter would require at least one addition to the standard prelude so as to provide the handler routine(s).
<langsyntaxhighlight lang="algol68">BEGIN
print (max int);
print (1+max int)
END</langsyntaxhighlight>
{{out}}
<pre>+2147483647
Line 302 ⟶ 303:
Note that, unlike many other languages, there is no presupposition that Algol 68 is running on a binary computer. The second example code below shows that for variables of mode '''long int''' arithmetic is fundamentally decimal in Algol 68 Genie.
 
<langsyntaxhighlight lang="algol68">BEGIN
print (long max int);
print (1+ long max int)
END
</syntaxhighlight>
</lang>
 
{{out}}
Line 314 ⟶ 315:
1
a68g: runtime error: 1: LONG INT value out of bounds (numerical result out of range) (detected in VOID closed-clause starting at "BEGIN" in line 1).</pre>
 
=={{header|Applesoft BASIC}}==
The integer variable type is a signed 16-bit integer with a range from -32767 to 32767. When an integer variable is assigned a value less than -32767 or greater than 32767, an "?ILLEGAL QUANTITY ERROR" message is displayed and no change is made to the current value of the variable. All of the expressions for assigning the values use floating point.
<syntaxhighlight lang="text">A% = -(-32767-1)</syntaxhighlight>
{{out}}<pre>?ILLEGAL QUANTITY ERROR</pre>
<syntaxhighlight lang="text">A% = 20000 + 20000</syntaxhighlight>
{{out}}<pre>?ILLEGAL QUANTITY ERROR</pre>
<syntaxhighlight lang="text">A% = -32767 -32767</syntaxhighlight>
{{out}}<pre>?ILLEGAL QUANTITY ERROR</pre>
<syntaxhighlight lang="text">A% = 182 * 182</syntaxhighlight>
{{out}}<pre>?ILLEGAL QUANTITY ERROR</pre>
It is possible using a POKE statement to assign the value -32768 which would normally be out of range.
<syntaxhighlight lang="text">A% = -32767 : POKE PEEK(131) + PEEK(132) * 256, 0 : ? A%</syntaxhighlight>
{{out}}<pre>-32768</pre>
 
=={{header|Arturo}}==
Line 319 ⟶ 334:
Arturo has unlimited-precision integers, without the possibility of an overflow, all with the same <code>:integer</code> type.
 
<langsyntaxhighlight lang="rebol">big32bit: 2147483646
big64bit: 9223372036854775808
 
Line 329 ⟶ 344:
 
print big32bit * 2
print big64bit * 2</langsyntaxhighlight>
 
{{out}}
Line 343 ⟶ 358:
Since AutoHotkey treats all integers as signed 64-bit, there is no point in demonstrating overflow with other integer types.
A AutoHotkey program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Msgbox, % "Testing signed 64-bit integer overflow with AutoHotkey:`n" -(-9223372036854775807-1) "`n" 5000000000000000000+5000000000000000000 "`n" -9223372036854775807-9223372036854775807 "`n" 3037000500*3037000500 "`n" (-9223372036854775807-1)//-1</langsyntaxhighlight>
{{out}}
<pre>Testing signed 64-bit integer overflow with AutoHotkey:
Line 358 ⟶ 373:
Overflow does <b>not</b> trigger an exception (because Axe does not support exceptions). After an overflow the program <b>continues with wrong results</b> (specifically, the value modulo 65536).
 
<langsyntaxhighlight lang="axe">Disp -65535▶Dec,i
Disp 40000+40000▶Dec,i
Disp 32767-65535▶Dec,i
Disp 257*257▶Dec,i</langsyntaxhighlight>
 
{{out}}
Line 374 ⟶ 389:
For those with a finite integer range, though, the most common stack cell size is a 32 bit signed integer, which will usually just wrap when overflowing (as shown in the sample output below). That said, it's not uncommon for the last expression to produce some kind of runtime error or OS exception, frequently even crashing the interpreter itself.
 
<langsyntaxhighlight lang="befunge">"a9jc>"*:*+*+:0\- "(-",,:.048*"="99")1 -" >:#,_$v
v,,,9"="*84 .: ,,"+"*84 .: **:*" }}" ,+55 .-\0-1<
>:+. 55+, ::0\- :. 48*"-",, \:. 48*"="9,,, -. 55v
v.*: ,,,,,999"="*84 .: ,,"*"*84 .: *+8*7"s9" ,+<
>55+, 0\- "(",:.048*"="99"1-/)1 -">:#,_$ 1-01-/.@</langsyntaxhighlight>
 
{{out}}
Line 395 ⟶ 410:
An overflow for signed integer arithmetic is undefined behavior.
A C program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int main (int argc, char *argv[])
Line 422 ⟶ 437:
printf("%lu\n", 4294967296LU * 4294967296LU);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 459 ⟶ 474:
The default behavior can be changed with a compiler flag.
 
<langsyntaxhighlight lang="csharp">using System;
public class IntegerOverflow
Line 507 ⟶ 522:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 543 ⟶ 558:
 
{{works with | g++ | 4.7}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdint>
#include <limits>
Line 577 ⟶ 592:
<< 4294967296LU * 4294967296LU << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 613 ⟶ 628:
 
By default, Clojure throws Exceptions on overflow conditions:
<langsyntaxhighlight lang="clojure">(* -1 (dec -9223372036854775807))
(+ 5000000000000000000 5000000000000000000)
(- -9223372036854775807 9223372036854775807)
(* 3037000500 3037000500)</langsyntaxhighlight>
{{out}} for all of the above statements:
<pre>ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow</pre>
 
If you want to silently overflow, you can set the special *unchecked-math* variable to true or use the special operations, unchecked-add, unchecked-multiply, etc..
<langsyntaxhighlight lang="clojure">(set! *unchecked-math* true)
(* -1 (dec -9223372036854775807)) ;=> -9223372036854775808
(+ 5000000000000000000 5000000000000000000) ;=> -8446744073709551616
Line 628 ⟶ 643:
; Note: The following division will currently silently overflow regardless of *unchecked-math*
; See: http://dev.clojure.org/jira/browse/CLJ-1253
(/ (dec -9223372036854775807) -1) ;=> -9223372036854775808</langsyntaxhighlight>
 
Clojure supports an arbitrary precision integer, BigInt and alternative math operators suffixed with an apostrophe: +', -', *', inc', and dec'. These operators auto-promote to BigInt upon overflow.
Line 634 ⟶ 649:
=={{header|COBOL}}==
COBOL uses decimal arithmetic, so the examples given in the specification are not directly relevant. This program declares a variable that can store three decimal digits, and attempts to assign a four-digit number to it. The result is that the number is truncated to fit, with only the three least significant digits actually being stored; and the program then proceeds. This behaviour may sometimes be what we want.
<langsyntaxhighlight lang="cobol">IDENTIFICATION DIVISION.
PROGRAM-ID. PROCRUSTES-PROGRAM.
DATA DIVISION.
Line 643 ⟶ 658:
MOVE 1002 TO X.
DISPLAY X UPON CONSOLE.
STOP RUN.</langsyntaxhighlight>
{{out}}
<pre>002</pre>
Line 662 ⟶ 677:
A small example:
 
<langsyntaxhighlight lang="cobol"> identification division.
program-id. overflowing.
 
Line 739 ⟶ 754:
 
goback.
end program overflowing.</langsyntaxhighlight>
 
{{out}}
Line 764 ⟶ 779:
=={{header|Computer/zero Assembly}}==
Arithmetic is performed modulo 256; overflow is not detected. This fragment:
<langsyntaxhighlight lang="czasm"> LDA ff
ADD one
 
Line 770 ⟶ 785:
 
ff: 255
one: 1</langsyntaxhighlight>
causes the accumulator to adopt the value 0. With a little care, the programmer can exploit this behaviour by treating each eight-bit word as either an unsigned byte or a signed byte using two's complement (although the instruction set does not provide explicit support for negative numbers). On the two's complement interpretation, the code given above would express the computation "–1 + 1 = 0".
 
Line 778 ⟶ 793:
Additionally, standard functions are available to perform arithmetic on int, long, uint, ulong values that modify a boolean value to signal when an overflow has occurred.
 
<langsyntaxhighlight lang="d">void main() @safe {
import std.stdio;
 
Line 814 ⟶ 829:
immutable r = muls(46_341, 46_341, overflow);
writeln("\n", r, " ", overflow);
}</langsyntaxhighlight>
{{out}}
<pre>Signed 32-bit:
Line 843 ⟶ 858:
 
-2147479015 true</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
As demonstrated by the program below, the Delphi catches these overflow conditions before they can be compiled.
 
 
<syntaxhighlight lang="Delphi">
 
 
var IS32: integer; {Signed 32-bit integer}
var IS64: Int64; {Signed 64-bit integer}
var IU32: cardinal; {Unsigned 32-bit integer}
 
{============ Signed 32 bit tests ===================================}
 
procedure TestSigned32_1;
begin
IS32:=-(-2147483647-1);
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
procedure TestSigned32_2;
begin
IS32:=2000000000 + 2000000000;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
 
procedure TestSigned32_3;
begin
IS32:=-2147483647 - 2147483647;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
procedure TestSigned32_4;
begin
IS32:=46341 * 46341;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
 
procedure TestSigned32_5;
begin
IS32:=(-2147483647-1) div -1;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
{============ Signed 64 bit tests ===================================}
 
procedure TestSigned64_1;
begin
IS64:=-(-9223372036854775807-1);
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestSigned64_2;
begin
IS64:=5000000000000000000+5000000000000000000;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestSigned64_3;
begin
IS64:=-9223372036854775807 - 9223372036854775807;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestSigned64_4;
begin
IS64:=3037000500 * 3037000500;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestSigned64_5;
begin
IS64:=(-9223372036854775807-1) div -1;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
{============ UnSigned 32 bit tests ===================================}
 
procedure TestUnSigned32_1;
begin
IU32:=-4294967295;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestUnSigned32_2;
begin
IU32:=3000000000 + 3000000000;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestUnSigned32_3;
begin
IU32:=2147483647 - 4294967295;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
procedure TestUnSigned32_4;
begin
IU32:=65537 * 65537;
end;
 
// Compiler: "Overflow in conversion or arithmetic operation"
 
 
//Delphi-6 does not have 64-bit unsigned integers.
//Later version have 64-bit unsigned integers.
 
</syntaxhighlight>
{{out}}
<pre>
 
</pre>
 
=={{header|Factor}}==
Line 852 ⟶ 1,006:
=={{header|FreeBASIC}}==
For the 64-bit integer type a FreeBASIC program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<syntaxhighlight lang ="c">#include <stdio.h></langsyntaxhighlight>
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' The suffixes L, LL, UL and ULL are added to the numbers to make it
Line 901 ⟶ 1,055:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 940 ⟶ 1,094:
[http://play.golang.org/p/jsPWC8KGzD Run this in the Go playground].
A Go program does <b>not</b> recognize an integer overflow and the program <b>continues with wrong results</b>.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,047 ⟶ 1,201:
u64 = 4294967296
fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64)
}</langsyntaxhighlight>
{{out}}
<pre>32 bit signed integers
Line 1,085 ⟶ 1,239:
Groovy does not recognize integer overflow in any bounded integral type and the program '''continues with wrong results'''. All bounded integral types use ''2's-complement'' arithmetic.
 
<langsyntaxhighlight lang="groovy">println "\nSigned 32-bit (failed):"
assert -(-2147483647-1) != 2147483648g
println(-(-2147483647-1))
Line 1,145 ⟶ 1,299:
println(3037000500g * 3037000500g)
assert (-9223372036854775807g-1g).intdiv(-1) == 9223372036854775808g
println((-9223372036854775807g-1g).intdiv(-1))</langsyntaxhighlight>
 
Output:
Line 1,184 ⟶ 1,338:
=={{header|Haskell}}==
Haskell supports both fixed sized signed integers (Int) and unbounded integers (Integer). Various sizes of signed and unsigned integers are available in Data.Int and Data.Word, respectively. The Haskell 2010 Language Report explains the following: "The results of exceptional conditions (such as overflow or underflow) on the fixed-precision numeric types are undefined; an implementation may choose error (⊥, semantically), a truncated value, or a special value such as infinity, indefinite, etc" (http://www.haskell.org/definition/haskell2010.pdf Section 6.4 Paragraph 4).
<langsyntaxhighlight Haskelllang="haskell">import Data.Int
import Data.Word
import Control.Exception
Line 1,209 ⟶ 1,363:
f ((10000000000000000000 + 10000000000000000000) :: Word64)
f ((9223372036854775807 - 18446744073709551615) :: Word64)
f ((4294967296 * 4294967296) :: Word64)</langsyntaxhighlight>
{{out}}
<pre>-2147483648
Line 1,236 ⟶ 1,390:
Also, negative numbers do not use - for the negative sign in J (a preceding - means to negate the argument on the right - in some cases this is the same kind of result, but in other cases it's different). Instead, use _ to denote negative numbers. Also, J does not use / for division, instead J uses % for division. With those changes, here's what the results look like in a 32 bit version of J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2.14748e9
2000000000 + 2000000000
Line 1,274 ⟶ 1,428:
_9.22337e18
4294967296 * 4294967296
1.84467e19</langsyntaxhighlight>
 
And, here's what it looks like in a 64 bit version of J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2147483648
2000000000 + 2000000000
Line 1,316 ⟶ 1,470:
_9.22337e18
4294967296 * 4294967296
1.84467e19</langsyntaxhighlight>
 
That said, note that the above was with default 6 digits of "printing precision". Here's how things look with that limit relaxed:
Line 1,322 ⟶ 1,476:
32 bit J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2147483648
2000000000 + 2000000000
Line 1,360 ⟶ 1,514:
_9223372036854775800
4294967296 * 4294967296
18446744073709552000</langsyntaxhighlight>
 
64 bit J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2147483648
2000000000 + 2000000000
Line 1,402 ⟶ 1,556:
_9223372036854775800
4294967296 * 4294967296
18446744073709552000</langsyntaxhighlight>
 
Finally, note that both versions of J support arbitrary precision integers. These are not the default, for performance reasons, but are available for cases where their performance penalty is acceptable.
Line 1,409 ⟶ 1,563:
The type int is a signed 32-bit integer and the type long is a 64-bit integer.
A Java program does <b>not</b> recognize an integer overflow and the program <b>continues with wrong results</b>.
<langsyntaxhighlight lang="java">public class integerOverflowIntegerOverflow {
 
public static void main(String[] args) {
System.out.println("Signed 32-bit:");
System.out.println(-(-2147483647 - 1));
System.out.println(2000000000 + 2000000000);
System.out.println(-2147483647 - 2147483647);
System.out.println(46341 * 46341);
System.out.println((-2147483647 - 1) / -1);
System.out.println("Signed 64-bit:");
System.out.println(-(-9223372036854775807L - 1));
System.out.println(5000000000000000000L + 5000000000000000000L);
System.out.println(-9223372036854775807L - 9223372036854775807L);
System.out.println(3037000500L * 3037000500L);
System.out.println((-9223372036854775807L - 1) / -1);
}
}</syntaxhighlight>
 
}</lang>
 
{{out}}
Line 1,436 ⟶ 1,588:
-2147479015
-2147483648
Signed 64-bit:
-9223372036854775808
-8446744073709551616
2
-9223372036709301616
-9223372036854775808
</pre>
 
===Using Java 8===
<syntaxhighlight lang="java">
public final class IntegerOverflow {
 
public static void main(String[] args) {
// The following examples show that Java allows integer overflow without warning
// and calculates an incorrect result.
// From version 8, Java introduced methods which throw an ArithmeticException when overflow occurs,
// which prevents the calculation of an incorrect result. It also allows the programmer to replace an "int"
// with a "long" and to replace a "long" with a BigInteger.
// Uncomment the lines below to see the use of the new methods:
// addExact(), subtractExact(), multiplyExact() and negateExact().
System.out.println("Signed 32-bit:");
System.out.println(-(-2_147_483_647 - 1));
// System.out.println(Math.negateExact(-2_147_483_647 - 1));
System.out.println(2_000_000_000 + 2_000_000_000);
// System.out.println(Math.addExact(2_000_000_000, 2_000_000_000));
System.out.println(-2_147_483_647 - 2_147_483_647);
// System.out.println(Math.subtractExact(-2_147_483_647, 2_147_483_647));
System.out.println(46_341 * 46_341);
// System.out.println(Math.multiplyExact(46_341, 46_341));
System.out.println((-2_147_483_647 - 1) / -1);
// System.out.println(Math.negateExact(Math.subtractExact(-2_147_483_647, 1) / 1));
System.out.println();
System.out.println("Signed 64-bit:");
System.out.println(-(-9_223_372_036_854_775_807L - 1));
// System.out.println(Math.negateExact(-9_223_372_036_854_775_807L - 1));
System.out.println(5_000_000_000_000_000_000L + 5_000_000_000_000_000_000L);
// System.out.println(Math.addExact(5_000_000_000_000_000_000L, 5_000_000_000_000_000_000L));
System.out.println(-9_223_372_036_854_775_807L - 9_223_372_036_854_775_807L);
// System.out.println(Math.subtractExact(-9_223_372_036_854_775_807L, 9_223_372_036_854_775_807L));
System.out.println(3_037_000_500L * 3_037_000_500L);
// System.out.println(Math.multiplyExact(3_037_000_500L, 3_037_000_500L));
System.out.println((-9_223_372_036_854_775_807L - 1) / -1);
// System.out.println(Math.negateExact(Math.subtractExact(-9_223_372_036_854_775_807L, 1) / 1));
}
 
}
</syntaxhighlight>
{{ out }}
<pre>
Signed 32-bit:
-2147483648
-294967296
2
-2147479015
-2147483648
 
Signed 64-bit:
-9223372036854775808
Line 1,460 ⟶ 1,679:
''The task''
 
<syntaxhighlight lang="jq">
<lang jq>
def compare:
if type == "string" then "\n\(.)\n"
Line 1,499 ⟶ 1,718:
[4294967296 * 4294967296, "18446744073709551616"]
 
| compare</langsyntaxhighlight>
 
===jq 1.6===
Line 1,567 ⟶ 1,786:
=={{header|Julia}}==
'''Plain Integer Types and Their Limits'''
<langsyntaxhighlight lang="julia">using Printf
S = subtypes(Signed)
U = subtypes(Unsigned)
Line 1,575 ⟶ 1,794:
@printf("%8s: [%s, %s]\n", s, typemin(s), typemax(s))
@printf("%8s: [%s, %s]\n", u, typemin(u), typemax(u))
end</langsyntaxhighlight>
{{out}}
<pre>Integer limits:
Line 1,593 ⟶ 1,812:
Julia does not throw an explicit error on integer overflow.
 
<langsyntaxhighlight lang="julia">println("Add one to typemax:")
for t in S
over = typemax(t) + one(t)
@printf("%8s → %-25s (%s)\n", t, over, typeof(over))
end</langsyntaxhighlight>
 
{{out}}
Line 1,610 ⟶ 1,829:
A Kotlin program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
 
<syntaxhighlight lang="kotlin">
<lang scala>// version 1.0.5-2
 
/* Kotlin (like Java) does not have unsigned integer types but we can simulate
what would happen if we did have an unsigned 32 bit integer type using this extension function */
fun Long.toUInt(): Long = this and 0xffffffffL
 
// The Kotlin compiler can detect expressions of signed constant integers that will overflow.
// It cannot detect unsigned integer overflow, however.
@Suppress("INTEGER_OVERFLOW")
fun main(args: Array<String>) {
// The following 'signed' computations all produce compiler warnings that they will lead to an overflow
// which have been ignored
println("*** Signed 32 bit integers ***\n")
println(-(-2147483647 - 1))
Line 1,632 ⟶ 1,847:
println(3037000500 * 3037000500)
println((-9223372036854775807 - 1) / -1)
// Simulated unsigned computations, no overflow warnings as we're using the Long type
println("\n*** Unsigned 32 bit integers ***\n")
// println(-4294967295U) // this is a compiler error since unsigned integers have no negation operator
println((-4294967295L).toUInt())
// println((3000000000L.toUInt(0U - 4294967295U) +// 3000000000L.toUInt()).toUInt())this works
println((2147483647L - 4294967295L4294967295).toUInt()). // converting from the signed Int type also produces the overflow; this is intended behavior of toUInt())
println((65537L3000000000U *+ 65537L).toUInt()3000000000U)
println(2147483647U - 4294967295U)
}</lang>
println(65537U * 65537U)
println("\n*** Unsigned 64 bit integers ***\n")
println(0U - 18446744073709551615U) // we cannot convert from a signed type here (since none big enough exists) and have to use subtraction
println(10000000000000000000U + 10000000000000000000U)
println(9223372036854775807U - 18446744073709551615U)
println(4294967296U * 4294967296U)
}</syntaxhighlight>
 
{{out}}
Line 1,664 ⟶ 1,885:
2147483648
131073
 
*** Unsigned 64 bit integers ***
 
1
1553255926290448384
9223372036854775808
0
</pre>
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
 
Line 1,690 ⟶ 1,918:
(( LONG_INT = 2**63 -1 )) ; print " LONG_INT (2^63 -1) = $LONG_INT"
(( LONG_INT = 2**63 )) ; print " LONG_INT (2^63) : $LONG_INT"
</syntaxhighlight>
</lang>
{{out}}<pre>
SHORT_INT (2^15 -1) = 32767
Line 1,703 ⟶ 1,931:
Lingo uses 32-bit signed integers.
A Lingo program does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<syntaxhighlight lang ="c">#include <stdio.h></langsyntaxhighlight>
 
<langsyntaxhighlight lang="lingo">put -(-2147483647-1)
-- -2147483648
 
Line 1,718 ⟶ 1,946:
 
put (-2147483647-1) / -1
--> crashes Director (jeez!)</langsyntaxhighlight>
 
=={{header|Lua}}==
Lua 5.3+ supports integer and floating sub-types of its generic number type. The ''standard'' implementation is 64-bit signed, under/overflow is not recognized.
<syntaxhighlight lang="lua">assert(math.type~=nil, "Lua 5.3+ required for this test.")
minint, maxint = math.mininteger, math.maxinteger
print("min, max int64 = " .. minint .. ", " .. maxint)
print("min-1 underflow = " .. (minint-1) .. " equals max? " .. tostring(minint-1==maxint))
print("max+1 overflow = " .. (maxint+1) .. " equals min? " .. tostring(maxint+1==minint))</syntaxhighlight>
{{out}}
<pre>min, max int64 = -9223372036854775808, 9223372036854775807
min-1 underflow = 9223372036854775807 equals max? true
max+1 overflow = -9223372036854775808 equals min? true</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Long A
Try ok {
Line 1,759 ⟶ 1,999:
Print Hex$(Eval(DataMem, 0!b))="BBBBAAAA"
Print Eval(DataMem, 0!b)=Eval(DataMem, 0!a2)*0x10000+Eval(DataMem, 0!a1)
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Mathematica and Wolfram Language uses arbitrary number types. There is a $MaxNumber which is approximately 1.60521676193366172702774105306375828321e1355718576299609, but extensive research has shown it to allow numbers up to <langsyntaxhighlight Mathematicalang="mathematica">$MaxNumber +
10^-15.954589770191003298111788092733772206160314 $MaxNumber</langsyntaxhighlight>I haven't bothered testing it to any more precision. If you try to use any number above that, it returns an Overflow[].
 
=={{header|Nim}}==
Line 1,772 ⟶ 2,012:
 
Catching an overflow (when --panics is off) is done this way:
<langsyntaxhighlight Nimlang="nim">try:
var x: int32 = -2147483647
x = -(x - 1) # Raise overflow.
echo x
except OverflowDefect:
echo "Overflow detected"</langsyntaxhighlight>
 
It is possible to tell the compiler to not generate code to detect overflows by using pragmas “push” and “pop”:
<langsyntaxhighlight Nimlang="nim">{.push overflowChecks: off.}
try:
var x: int32 = -2147483647
Line 1,787 ⟶ 2,027:
except OverflowDefect:
echo "Overflow detected" # Not executed.
{.pop.}</langsyntaxhighlight>
 
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.
Line 1,796 ⟶ 2,036:
This program presents the behavior when overflow checks are suppressed. Remember that for signed integers, this is not the normal behavior and that the result is always wrong when an overflow occurs.
 
<langsyntaxhighlight Nimlang="nim">echo "For 32 bits signed integers with overflow check suppressed:"
{.push overflowChecks: off.}
var a: int32
Line 1,847 ⟶ 2,087:
echo " 9223372036854775807 - 18446744073709551615 gives ", d # 9223372036854775808.
d = 4294967296u64 * 4294967296u64
echo " 4294967296 * 4294967296 gives ", d # 0.</langsyntaxhighlight>
 
{{out}}
Line 1,889 ⟶ 2,129:
=={{header|PARI/GP}}==
Machine-sized integers can be used inside a <code>Vecsmall</code>:
<langsyntaxhighlight lang="parigp">Vecsmall([1])
Vecsmall([2^64])</langsyntaxhighlight>
{{out}}
<pre>%1 = Vecsmall([1])
Line 1,911 ⟶ 2,151:
Using Perl 5.18 on 64-bit Linux with use integer:
The Perl 5 program below does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
<syntaxhighlight lang ="c">#include <stdio.h></langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">
use strict;
use warnings;
Line 1,925 ⟶ 2,165:
say(3037000500 * 3037000500);
say((-9223372036854775807-1) / -1);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,943 ⟶ 2,183:
Integer overflow is handled by automatic promotion to atom (an IEEE float, 64/80 bit for the 32/64 bit implementations respectively),
which triggers a run-time type check if stored in a variable declared as integer, eg:
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1000000000</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">1000000000</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,952 ⟶ 2,192:
</pre>
The <b>overflow is automatically caught</b> and the program <b>does not continue</b> with the wrong results. You are always given the exact source file and line number that the error occurs on, and several editors, including Edita which is bundled with the compiler, will automatically jump to the source code line at fault. Alternatively you may declare a variable as atom and get the same performance for small integers, with seamless conversion to floats (with 53 or 64 bits of precision) as needed. Phix has no concept of unsigned numbers, except as user defined types that trigger errors when negative values are detected, but otherwise have the same ranges as above.
 
You can of course use a standard try/catch statement to avoid termination and resume processing (after the end try) and that way make a program more "robust". However a mute top-level "catch-all" that says and logs nothing will most certainly simply serve to make the program ''much harder to debug'', whereas localising all try/catch statements to cover the least possible amount of code makes it much easier to "do the right thing" should an error occur.
 
=={{header|PicoLisp}}==
Line 1,963 ⟶ 2,205:
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)<br>
8080 PL/M does not check for overflow, incrementing the largest integer values wraps around to 0 (numbers are insigned in 8080 PL/M) and the program <b>continues with wrong results</b>.
<langsyntaxhighlight lang="pli">100H: /* SHOW INTEGER OVERFLOW */
 
/* CP/M SYSTEM CALL */
Line 2,005 ⟶ 2,247:
CALL PRNL;
 
EOF</langsyntaxhighlight>
{{out}}
<pre>
Line 2,017 ⟶ 2,259:
https://docs.microsoft.com/en-us/dotnet/api/system.decimal?view=netframework-4.8#remarks
 
<langsyntaxhighlight lang="powershell">
try {
# All of these raise an exception, which is caught below.
Line 2,048 ⟶ 2,290:
$Error.Exception
}
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
CPU=x64, OS=Windows7
<langsyntaxhighlight lang="purebasic">#MAX_BYTE =127
 
#MAX_ASCII=255 ;=MAX_CHAR Ascii-Mode
Line 2,107 ⟶ 2,349:
say("Quad",q1,q2,SizeOf(q1))
 
Input()</langsyntaxhighlight>
{{out}}
<pre>
Line 2,125 ⟶ 2,367:
Python 2.X has a 32 bit signed integer type called 'int' that automatically converts to type 'long' on overflow. Type long is of arbitrary precision adjusting its precision up to computer limits, as needed.
 
<langsyntaxhighlight lang="python">Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> for calc in ''' -(-2147483647-1)
Line 2,142 ⟶ 2,384:
Expression: '46341 * 46341' evaluates to 2147488281 of type <type 'long'>
Expression: '(-2147483647-1) / -1' evaluates to 2147483648 of type <type 'long'>
>>> </langsyntaxhighlight>
 
===Python 3.x===
Python 3.X has the one 'int' type that is of arbitrary precision. Implementations ''may'' use 32 bit integers for speed and silently shift to arbitrary precision to avoid overflow.
<langsyntaxhighlight lang="python">Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> for calc in ''' -(-2147483647-1)
Line 2,163 ⟶ 2,405:
Expression: '46341 * 46341' evaluates to 2147488281 of type <class 'int'>
Expression: '(-2147483647-1) / -1' evaluates to 2147483648.0 of type <class 'float'>
>>> </langsyntaxhighlight>
 
Note: In Python 3.X the division operator used between two ints returns a floating point result, (as this was seen as most often required and expected in the Python community). Use <code>//</code> to get integer division.
Line 2,178 ⟶ 2,420:
The unsafe operations expects fixnums in the arguments, and that the result is also a fixnum. They don't autopromote the result. They are faster but they should be used only in special cases, where the values known to be bounded. We can use them to see the behavior after an overflow. In case of a overflow they have undefined behaviour, so they may give different results or change without warning in future versions. (I don't expect that they will change soon, but there is no official guaranty.)
 
<langsyntaxhighlight Racketlang="racket">#lang racket
(require racket/unsafe/ops)
 
Line 2,197 ⟶ 2,439:
 
(/ -1073741824 -1) ;==> 1073741824
(unsafe-fxquotient -1073741824 -1) ;==> -1073741824</langsyntaxhighlight>
 
The 64-bit version is similar. The fixnum are effectively 63-bits signed integers.
Line 2,206 ⟶ 2,448:
The Raku program below does <b>not</b> recognize a signed integer overflow and the program <b>continues with wrong results</b>.
 
<syntaxhighlight lang="raku" perl6line>my int64 ($a, $b, $c) = 9223372036854775807, 5000000000000000000, 3037000500;
.say for -(-$a - 1), $b + $b, -$a - $a, $c * $c, (-$a - 1)/-1;</langsyntaxhighlight>
{{out}}
<pre>-9223372036854775808
Line 2,223 ⟶ 2,465:
For newer versions of REXX, the &nbsp; '''signal on lostDigits''' &nbsp; statement can be used to accomplish the same results &nbsp;
<br>(for detecting a loss of significance [digits]).
<langsyntaxhighlight lang="rexx">/*REXX program displays values when integers have an overflow or underflow. */
numeric digits 9 /*the REXX default is 9 decimal digits.*/
call showResult( 999999997 + 1 )
Line 2,238 ⟶ 2,480:
else _=' [underflow]' /*did it underflow? */
say right(x, 20) _ /*show the result. */
return x /*return the value. */</langsyntaxhighlight>
'''output''' &nbsp; using the default input(s): <br><br>
Output note: &nbsp; (as it happens, all of the results below are numerically correct)
Line 2,249 ⟶ 2,491:
-1.00000000E+9 [underflow]
-1.50000000E+9 [underflow]
</pre>
 
=={{header|RPL}}==
RPL can handle unsigned integers, whose size can be set by the user from 2 to 64 bits. This format is provided to help software engineers in low-level programming of a ‘real’ computer, not to speed up calculations: RPL programs go faster when using floating-point numbers.
Let’s work with 64-bit integers, displayed in base 10:
64 STWS DEC
and let’s try to comply with the task:
# -18446744073709551615
is rejected by the command line interpreter (syntax error).
#10000000000000000000 #10000000000000000000 +
#9223372036854775807 #18446744073709551615 -
#4294967296 #4294967296 *
{{out}}
<pre>
3: # 9223372036854775807d
2: # 0d
1: # 0d
</pre>
 
Line 2,257 ⟶ 2,516:
Bignum objects are created automatically when integer calculations would otherwise overflow a Fixnum.
When a calculation involving Bignum objects returns a result that will fit in a Fixnum, the result is automatically converted.
<langsyntaxhighlight lang="ruby">2.1.1 :001 > a = 2**62 -1
=> 4611686018427387903
2.1.1 :002 > a.class
Line 2,265 ⟶ 2,524:
2.1.1 :004 > (b-1).class
=> Fixnum
</syntaxhighlight>
</lang>
Since Ruby 2.4 these different classes have disappeared: all numbers in above code are of class Integer.
 
Line 2,291 ⟶ 2,550:
The following code will always panic when run in any mode
 
<syntaxhighlight lang="rust">
<lang Rust>
// The following will panic!
let i32_1 : i32 = -(-2_147_483_647 - 1);
Line 2,305 ⟶ 2,564:
let i64_4 : i64 = 3_037_000_500 * 3_037_000_500;
let i64_5 : i64 = (-9_223_372_036_854_775_807 - 1) / -1;
</syntaxhighlight>
</lang>
 
In order to declare overflow/underflow behaviour as intended (and, thus, valid in both debug and release modes), Rust provides two mechanisms:
Line 2,319 ⟶ 2,578:
<br>
 
<syntaxhighlight lang="rust">
<lang Rust>
// The following will never panic!
println!("{:?}", 65_537u32.checked_mul(65_537)); // None
Line 2,329 ⟶ 2,588:
println!("{:?}", 65_537i32.saturating_mul(65_537)); // 2147483647
println!("{:?}", 65_537i32.wrapping_mul(-65_537)); // -131073
</syntaxhighlight>
</lang>
 
Second, a generic <code>Wrapping<T></code> one-element tuple type is provided which implements the same basic operations as the <code>wrapping_...</code> methods, but allows you to use normal operators and then use the <code>.0</code> field accessor to retrieve the value once you are finished.<ref>{{Cite web |url=https://doc.rust-lang.org/std/num/struct.Wrapping.html |title=Struct std::num::Wrapping |website=The Rust Standard Library |access-date=2019-11-18}}</ref>
Line 2,336 ⟶ 2,595:
{{works with|Java|8}}
Math.addExact works for both 32-bit unsigned and 64-bit unsigned integers, but Java does not support signed integers.
<langsyntaxhighlight Scalalang="scala">import Math.{addExact => ++, multiplyExact => **, negateExact => ~~, subtractExact => --}
 
def requireOverflow(f: => Unit) =
Line 2,350 ⟶ 2,609:
println("Test - Expect Undetected overflow:")
requireOverflow(++(1,1)) // Undetected overflow
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
Line 2,356 ⟶ 2,615:
The type [http://seed7.sourceforge.net/manual/types.htm#integer integer] is a 64-bit signed integer type.
All computations with the type integer are checked for overflow.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const proc: writeResult (ref func integer: expression) is func
Line 2,374 ⟶ 2,633:
writeResult(3037000500 * 3037000500);
writeResult((-9223372036854775807-1) div -1);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,388 ⟶ 2,647:
{{trans|Raku}}
Sidef has unlimited precision integers.
<langsyntaxhighlight lang="ruby">var (a, b, c) = (9223372036854775807, 5000000000000000000, 3037000500);
[-(-a - 1), b + b, -a - a, c * c, (-a - 1)/-1].each { say _ };</langsyntaxhighlight>
{{out}}
<pre>
Line 2,403 ⟶ 2,662:
However, to emulate wrong behavior (eg. when interfacing to external programs or document formats), it can be emulated.
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">2147483647 + 1. -> 2147483648
2147483647 add_32: 1 -> -2147483648
4294967295 + 1. -> 4294967296
16rFFFFFFFF add_32u: 1. -> 0
... simular stuff for sub32/mul32 ...</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">// By default, all overflows in Swift result in a runtime exception, which is always fatal
// However, you can opt-in to overflow behavior with the overflow operators and continue with wrong results
 
Line 2,461 ⟶ 2,720:
println(uInt64)
uInt64 = 4294967296 &* 4294967296
println(uInt64)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,493 ⟶ 2,752:
=={{header|Standard ML}}==
PolyML
<langsyntaxhighlight Standardlang="standard MLml">~(~9223372036854775807-1) ;
poly: : error: Overflow exception raised while converting ~9223372036854775807 to int
Int.maxInt ;
Line 2,503 ⟶ 2,762:
2147483648 * 2147483648 ;
Exception- Overflow raised
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Tcl (since 8.5) uses logical signed integers throughout that are “large enough to hold the number you are using” (being internally anything from a single machine word up to a bignum). The only way to get 32-bit and 64-bit values in arithmetic is to apply a clamping function at appropriate points:
<langsyntaxhighlight lang="tcl">proc tcl::mathfunc::clamp32 {x} {
expr {$x<0 ? -((-$x) & 0x7fffffff) : $x & 0x7fffffff}
}
puts [expr { clamp32(2000000000 + 2000000000) }]; # ==> 1852516352</langsyntaxhighlight>
Tcl 8.4 used a mix of 32-bit and 64-bit numbers on 32-bit platforms and 64-bit numbers only on 64-bit platforms. Users are recommended to upgrade to avoid this complexity.
 
=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">PRINT "Signed 32-bit:"
PRINT -(-2147483647-1) !-2147483648
PRINT 2000000000 + 2000000000 !4000000000
PRINT -2147483647 - 2147483647 !-4294967294
PRINT 46341 * 46341 !2147488281
!PRINT (-2147483647-1) / -1 !error: Illegal expression
WHEN ERROR IN
PRINT maxnum * 2 !Run-time error "Overflow"
USE
PRINT maxnum
!returns the largest number that can be represented in your computer
END WHEN
END</syntaxhighlight>
 
=={{header|VBScript}}==
Line 2,519 ⟶ 2,793:
<br>- Yes, because typename(2147483647)="Long" and typename(2147483648)="Double", so we have switched from fixed binary integer to double floating point. But thanks to mantissa precision there is no harm. The integer overflow is when you reach 10^15, because you are now out of the integer set : (1E+15)+1=1E+15 !?.
<br>A good way to test integer overflow is to use the vartype() or typename() builtin functions.
<langsyntaxhighlight lang="vb">'Binary Integer overflow - vbs
i=(-2147483647-1)/-1
wscript.echo i
Line 2,532 ⟶ 2,806:
i1=1000000000000000-1 '1E+15-1
i2=i1+1 '1E+15
wscript.echo Cstr(i1) & " , " & Cstr(i2)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,546 ⟶ 2,820:
{{works with|Visual Basic|VB6 Standard}}
Overflow is well handled, except for a strange bug in the computation of f the constant -(-2147483648).
<langsyntaxhighlight lang="vb"> 'Binary Integer overflow - vb6 - 28/02/2017
Dim i As Long '32-bit signed integer
i = -(-2147483647 - 1) '=-2147483648 ?! bug
Line 2,558 ⟶ 2,832:
i = 46341 * 46341 'Run-time error '6' : Overflow
i = (-2147483647 - 1) / -1 'Run-time error '6' : Overflow
</langsyntaxhighlight>
'''Error handling - method 1'''
<langsyntaxhighlight lang="vb"> i=0
On Error Resume Next
i = 2147483647 + 1
Debug.Print i 'i=0
</syntaxhighlight>
</lang>
'''Error handling - method 2'''
<langsyntaxhighlight lang="vb"> i=0
On Error GoTo overflow
i = 2147483647 + 1
Line 2,572 ⟶ 2,846:
overflow:
Debug.Print "Error: " & Err.Description '-> Error: Overflow
</syntaxhighlight>
</lang>
'''Error handling - method 3'''
<langsyntaxhighlight lang="vb"> On Error GoTo 0
i = 2147483647 + 1 'Run-time error '6' : Overflow
Debug.Print i
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
Line 2,588 ⟶ 2,862:
 
'''32-bit signed integer'''
<langsyntaxhighlight lang="vbnet"> Dim i As Integer '32-bit signed integer</langsyntaxhighlight>
Pre-compilation error:
'Error: Constant expression not representable in type 'Integer'
for:
<langsyntaxhighlight lang="vbnet"> i = -(-2147483647 - 1)
i = 0 - (-2147483647 - 1)
i = -(-2147483647L - 1)
Line 2,600 ⟶ 2,874:
i = -2147483647 - 2147483647
i = 46341 * 46341
i = (-2147483647 - 1) / -1 </langsyntaxhighlight>
Execution error:
'An unhandled exception of type 'System.OverflowException' occurred
'Additional information: Arithmetic operation resulted in an overflow.
for:
<langsyntaxhighlight lang="vbnet"> i = -Int(-2147483647 - 1)
i = -2147483647: i = -(i - 1) </langsyntaxhighlight>
'''32-bit unsigned integer'''<br>
In Visual Basic .Net there is no specific UInteger constants as in C.
<langsyntaxhighlight lang="vbnet"> Dim i As UInteger '32-bit unsigned integer</langsyntaxhighlight>
Pre-compilation error:
'Error: Constant expression not representable in type 'UInteger'
for:
<langsyntaxhighlight lang="vbnet"> i = -4294967295
i = 3000000000 + 3000000000
i = 2147483647 - 4294967295
i = 65537 * 65537 </langsyntaxhighlight>
Execution error:
'An unhandled exception of type 'System.OverflowException' occurred
'Additional information: Arithmetic operation resulted in an overflow.
for:
<langsyntaxhighlight lang="vbnet"> i = 3000000000 : i = i + i </langsyntaxhighlight>
'''64-bit signed integer'''
<langsyntaxhighlight lang="vbnet"> Dim i As Long '64-bit signed integer</langsyntaxhighlight>
Pre-compilation error:
'Error: Constant expression not representable in type 'Long'
for:
<langsyntaxhighlight lang="vbnet"> i = -(-9223372036854775807 - 1)
i = 5000000000000000000 + 5000000000000000000
i = -9223372036854775807 - 9223372036854775807
i = 3037000500 * 3037000500
i = (-9223372036854775807 - 1) / -1</langsyntaxhighlight>
Execution error:
'An unhandled exception of type 'System.OverflowException' occurred
'Additional information: Arithmetic operation resulted in an overflow.
for:
<langsyntaxhighlight lang="vbnet"> i = -9223372036854775807 : i = -(i - 1)</langsyntaxhighlight>
 
'''64-bit unsigned integer'''<br>
In Visual Basic .Net there is no specific ULong constants as in C.
And 'Long' constants are not good enough.
<langsyntaxhighlight lang="vbnet"> Dim i As ULong '64-bit unsigned integer</langsyntaxhighlight>
Pre-compilation error:
'Error: Overflow
for:
<langsyntaxhighlight lang="vbnet"> i = -18446744073709551615
i = 10000000000000000000 + 10000000000000000000
i = 9223372036854775807 - 18446744073709551615</langsyntaxhighlight>
Pre-compilation error:
'Error: Constant expression not representable in type 'Long'
for:
<langsyntaxhighlight lang="vbnet"> i = 4294967296 * 4294967296</langsyntaxhighlight>
Execution error:
'An unhandled exception of type 'System.OverflowException' occurred
'Additional information: Arithmetic operation resulted in an overflow.
for:
<langsyntaxhighlight lang="vbnet"> i = 4294967296 : i = i * i</langsyntaxhighlight>
 
'''how the exception is catched'''
<langsyntaxhighlight lang="vbnet"> Dim i As Integer '32-bit signed integer
Try
i = -2147483647 : i = -(i - 1)
Line 2,665 ⟶ 2,939:
Catch ex As Exception
Debug.Print("Exception raised : " & ex.Message)
End Try</langsyntaxhighlight>
{{out}}
<pre>
Line 2,678 ⟶ 2,952:
 
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.
<langsyntaxhighlight ecmascriptlang="wren">var exprs = [-4294967295, 3000000000 + 3000000000, 2147483647 - 4294967295, 65537 * 65537]
 
for (expr in exprs) System.print(expr >> 0)</lang>
System.print("Unsigned 32-bit:")
for (expr in exprs) System.print(expr >> 0)</syntaxhighlight>
 
{{out}}
Results agree with those for the corresponding C entry above.
Line 2,698 ⟶ 2,972:
continues with wrong results.
 
<langsyntaxhighlight XPL0lang="xpl0">int N;
[N:= -(-2147483647-1);
IntOut(0, N); CrLf(0);
Line 2,709 ⟶ 2,983:
N:= (-2147483647-1)/-1;
IntOut(0, N); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,729 ⟶ 3,003:
* <code>PO</code> parity odd, no overflow
 
<langsyntaxhighlight lang="z80">ld a,&7F
add 1
jp pe,ErrorHandler ;pe = parity even, but in this case it represents overflow set</langsyntaxhighlight>
 
Like other CPUs, the Z80 has no way of knowing whether a value is intended to be signed or unsigned, and unless you explicitly have a jump, call, or return based on overflow after a calculation, the CPU '''will continue with the wrong result.'''
Line 2,741 ⟶ 3,015:
zkl uses C's 64 bit integer math and the results are OS dependent. Integers are signed. GMP can be used for big ints.
A zkl program does <b>not</b> recognize an integer overflow and the program <b>continues with wrong results</b>.
<langsyntaxhighlight lang="zkl">print("Signed 64-bit:\n");
println(-(-9223372036854775807-1));
println(5000000000000000000+5000000000000000000);
println(-9223372036854775807 - 9223372036854775807);
println(3037000500 * 3037000500);
println((-9223372036854775807-1) / -1);</langsyntaxhighlight>
{{out}}
Linux/BSD/clang
871

edits