Integer overflow: Difference between revisions

New post showing additional methods introduced in Java 8, in addition to an existing post which was retained.
(Added XPL0 example.)
(New post showing additional methods introduced in Java 8, in addition to an existing post which was retained.)
 
(46 intermediate revisions by 20 users not shown)
Line 25:
 
For 32-bit signed integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit signed integer
Line 46:
 
For 64-bit signed integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit signed integer
Line 67:
 
For 32-bit unsigned integers:
::::: {|class="wikitable"
!Expression
!Result that does not fit into a 32-bit unsigned integer
Line 85:
 
For 64-bit unsigned integers:
::: {|class="wikitable"
!Expression
!Result that does not fit into a 64-bit unsigned integer
Line 102:
|}
 
 
When the integer overflow does trigger an exception show how the exception is caught.
;Notes:
When the integer overflow produces some value print it.
It:* should  beWhen explicitly noted when anthe integer overflow isdoes nottrigger recognizedan andexception theshow programhow continuesthe withexception wrongis resultscaught.
:*   When the integer overflow produces some value,   print it.
This should be done for signed and unsigned integers of various sizes supported by the language.
:*   It should be explicitly noted when an integer overflow is not recognized,   the program continues with wrong results.
When a language has no fixed size integer type or when no integer overflow can occur
:*   This should be done for signed and unsigned integers of various sizes supported by the computer programming language.
for other reasons this should be noted.
:*   When a language has no fixed size integer type,   or when no integer overflow can occur for other reasons,   this should be noted.
It is okay to mention, when a language supports unlimited precision integers, but
:* &nbsp; It is okay to mention, &nbsp; when a language supports unlimited precision integers, &nbsp; but this task is NOT the place to demonstrate the <br>&nbsp; capabilities of unlimited precision integers.
<br><br>
 
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 (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:
* <code>BVS</code> Branch if Overflow Set (signed overflow has occurred)
* <code>BVC</code> Branch if Overflow Clear (signed overflow did not occur)
* <code>BCS</code> Branch if Carry Set (unsigned overflow has occurred)
* <code>BCC</code> Branch if Carry Clear (unsigned overflow did not occur)
 
These flags will automatically be set or cleared depending on the results of a calculation that can affect them.
 
<syntaxhighlight lang="6502asm">LDA #$7F
CLC
ADC #$01
BVS ErrorHandler ;this branch will always be taken.</syntaxhighlight>
 
<syntaxhighlight lang="6502asm">LDA #$FF
CLC
ADC #$01
BCS ErrorHandler ;this branch will always be taken.</syntaxhighlight>
 
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:
 
<syntaxhighlight 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.</syntaxhighlight>
 
<syntaxhighlight 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.</syntaxhighlight>
 
 
The same is true for unsigned overflow, but less so since the zero flag can be used as a substitute in these cases.
<syntaxhighlight 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.</syntaxhighlight>
 
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).
 
===16-Bit or Higher Overflow===
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.
 
<syntaxhighlight 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.
 
;add the low bytes
 
LDA $10 ;low byte of first operand
CLC
ADC $12 ;low byte of second operand
STA $14 ;low byte of sum
 
;add the high bytes
 
LDA $11 ;high byte of first operand
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.</syntaxhighlight>
 
=={{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)
 
<syntaxhighlight 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</syntaxhighlight>
 
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:
* <code>TRAPV</code> will call an exception handler if the overflow flag is set, otherwise it will do nothing.
* <code>DBVS Dn</code> will loop a section of code until the overflow flag is set or the chosen data register is decremented to 0xFFFF, whichever occurs first.
* <code>BVS</code> branches if the overflow flag is set.
 
=={{header|Ada}}==
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 185 ⟶ 260:
A := A + 1; -- line 49 -- this will later raise a CONSTRAINT_ERROR
end loop;
end Overflow;</langsyntaxhighlight>
 
{{out}}
Line 216 ⟶ 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 228 ⟶ 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 240 ⟶ 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}}==
 
Arturo has unlimited-precision integers, without the possibility of an overflow, all with the same <code>:integer</code> type.
 
<syntaxhighlight lang="rebol">big32bit: 2147483646
big64bit: 9223372036854775808
 
print type big32bit
print type big64bit
 
print big32bit + 1
print big64bit + 1
 
print big32bit * 2
print big64bit * 2</syntaxhighlight>
 
{{out}}
 
<pre>:integer
:integer
2147483647
9223372036854775809
4294967292
18446744073709551616</pre>
 
=={{header|AutoHotkey}}==
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 259 ⟶ 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 275 ⟶ 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 296 ⟶ 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 323 ⟶ 437:
printf("%lu\n", 4294967296LU * 4294967296LU);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 360 ⟶ 474:
The default behavior can be changed with a compiler flag.
 
<langsyntaxhighlight lang="csharp">using System;
public class IntegerOverflow
Line 408 ⟶ 522:
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 444 ⟶ 558:
 
{{works with | g++ | 4.7}}
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <cstdint>
#include <limits>
Line 478 ⟶ 592:
<< 4294967296LU * 4294967296LU << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 514 ⟶ 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 529 ⟶ 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 535 ⟶ 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 544 ⟶ 658:
MOVE 1002 TO X.
DISPLAY X UPON CONSOLE.
STOP RUN.</langsyntaxhighlight>
{{out}}
<pre>002</pre>
Line 563 ⟶ 677:
A small example:
 
<langsyntaxhighlight lang="cobol"> identification division.
program-id. overflowing.
 
Line 640 ⟶ 754:
 
goback.
end program overflowing.</langsyntaxhighlight>
 
{{out}}
Line 665 ⟶ 779:
=={{header|Computer/zero Assembly}}==
Arithmetic is performed modulo 256; overflow is not detected. This fragment:
<langsyntaxhighlight lang="czasm"> LDA ff
ADD one
 
Line 671 ⟶ 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 679 ⟶ 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 715 ⟶ 829:
immutable r = muls(46_341, 46_341, overflow);
writeln("\n", r, " ", overflow);
}</langsyntaxhighlight>
{{out}}
<pre>Signed 32-bit:
Line 744 ⟶ 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 753 ⟶ 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>.
<langsyntaxhighlight lang="c">#include <stdio.h></syntaxhighlight>
 
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' The suffixes L, LL, UL and ULL are added to the numbers to make it
Line 802 ⟶ 1,055:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 841 ⟶ 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 948 ⟶ 1,201:
u64 = 4294967296
fmt.Printf(" %d * %d: %d\n", u64, u64, u64*u64)
}</langsyntaxhighlight>
{{out}}
<pre>32 bit signed integers
Line 986 ⟶ 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,046 ⟶ 1,299:
println(3037000500g * 3037000500g)
assert (-9223372036854775807g-1g).intdiv(-1) == 9223372036854775808g
println((-9223372036854775807g-1g).intdiv(-1))</langsyntaxhighlight>
 
Output:
Line 1,085 ⟶ 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,110 ⟶ 1,363:
f ((10000000000000000000 + 10000000000000000000) :: Word64)
f ((9223372036854775807 - 18446744073709551615) :: Word64)
f ((4294967296 * 4294967296) :: Word64)</langsyntaxhighlight>
{{out}}
<pre>-2147483648
Line 1,137 ⟶ 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,175 ⟶ 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,217 ⟶ 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,223 ⟶ 1,476:
32 bit J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2147483648
2000000000 + 2000000000
Line 1,261 ⟶ 1,514:
_9223372036854775800
4294967296 * 4294967296
18446744073709552000</langsyntaxhighlight>
 
64 bit J:
 
<langsyntaxhighlight Jlang="j"> -(_2147483647-1)
2147483648
2000000000 + 2000000000
Line 1,303 ⟶ 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,310 ⟶ 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,344 ⟶ 1,595:
-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
-8446744073709551616
2
-9223372036709301616
-9223372036854775808
</pre>
 
=={{header|jq}}==
 
The C-based implementation of jq uses IEEE 754 64-bit numbers for numeric computations
without raising errors except for division by 0.
 
The Go-based implementation of jq, gojq, uses unbounded precision for integer computations
involving infix operators (+, -, %, /), but in the case of division, the result is only guaranteed to be
precise if the divisor is a factor of the dividend. Using gojq, the error raised by an attempt to divide
a number by 0 is catchable.
 
In the following section, a jq program that implements the task is presented.
The outputs produced by jq and by gojq
are then given.
 
''The task''
 
<syntaxhighlight lang="jq">
def compare:
if type == "string" then "\n\(.)\n"
else map(tostring)
| .[1] as $s
| .[0]
| if $s == . then . + ": agrees"
else $s + ": expression evaluates to " + .
end
end;
[ -(-2147483647-1),"2147483648"],
[2000000000 + 2000000000, "4000000000"],
[-2147483647 - 2147483647, "-4294967294"],
[46341 * 46341, "2147488281"],
[(-2147483647-1) / -1, "2147483648"],
 
"For 64-bit signed integers:",
 
[-(-9223372036854775807-1), "9223372036854775808"],
[5000000000000000000+5000000000000000000, "10000000000000000000"],
[-9223372036854775807 - 9223372036854775807, "-18446744073709551614"],
[3037000500 * 3037000500, "9223372037000250000"],
[(-9223372036854775807-1) / -1, "9223372036854775808"],
 
"For 32-bit unsigned integers:",
 
[-4294967295, "-4294967295"],
[3000000000 + 3000000000, "6000000000"],
[2147483647 - 4294967295, "-2147483648"],
[65537 * 65537, "4295098369"],
 
"For 64-bit unsigned integers:",
 
[-18446744073709551615, "-18446744073709551615"],
[10000000000000000000 + 10000000000000000000, "20000000000000000000"],
[9223372036854775807 - 18446744073709551615, "-9223372036854775808"],
[4294967296 * 4294967296, "18446744073709551616"]
 
| compare</syntaxhighlight>
 
===jq 1.6===
<pre>2147483648: agrees
4000000000: agrees
-4294967294: agrees
2147488281: agrees
2147483648: agrees
 
For 64-bit signed integers:
 
9223372036854775808: expression evaluates to 9223372036854776000
10000000000000000000: expression evaluates to 1e+19
-18446744073709551614: expression evaluates to -18446744073709552000
9223372037000250000: agrees
9223372036854775808: expression evaluates to 9223372036854776000
 
For 32-bit unsigned integers:
 
-4294967295: agrees
6000000000: agrees
-2147483648: agrees
4295098369: agrees
 
For 64-bit unsigned integers:
 
-18446744073709551615: expression evaluates to -18446744073709552000
20000000000000000000: expression evaluates to 2e+19
-9223372036854775808: expression evaluates to -9223372036854776000
18446744073709551616: expression evaluates to 18446744073709552000
</pre>
 
===gojq===
<pre>
gojq -nr -f rc-integer-overflow.jq
2147483648: agrees
4000000000: agrees
-4294967294: agrees
2147488281: agrees
2147483648: agrees
 
For 64-bit signed integers:
 
9223372036854775808: agrees
10000000000000000000: agrees
-18446744073709551614: agrees
9223372037000250000: agrees
9223372036854775808: agrees
 
For 32-bit unsigned integers:
 
-4294967295: agrees
6000000000: agrees
-2147483648: agrees
4295098369: agrees
 
For 64-bit unsigned integers:
 
-18446744073709551615: agrees
20000000000000000000: agrees
-9223372036854775808: agrees
18446744073709551616: agrees
</pre>
 
 
 
=={{header|Julia}}==
'''Plain Integer Types and Their Limits'''
<langsyntaxhighlight lang="julia">using Printf
S = subtypes(Signed)
U = subtypes(Unsigned)
Line 1,355 ⟶ 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,373 ⟶ 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,390 ⟶ 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,412 ⟶ 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,444 ⟶ 1,885:
2147483648
131073
 
*** Unsigned 64 bit integers ***
 
1
1553255926290448384
9223372036854775808
0
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Integer overflow
 
# # Variables:
#
typeset -si SHORT_INT
typeset -i INTEGER
typeset -li LONG_INT
 
######
# main #
######
 
(( SHORT_INT = 2**15 -1 )) ; print "SHORT_INT (2^15 -1) = $SHORT_INT"
(( SHORT_INT = 2**15 )) ; print "SHORT_INT (2^15) : $SHORT_INT"
 
(( INTEGER = 2**31 -1 )) ; print " INTEGER (2^31 -1) = $INTEGER"
(( INTEGER = 2**31 )) ; print " INTEGER (2^31) : $INTEGER"
 
(( 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>
{{out}}<pre>
SHORT_INT (2^15 -1) = 32767
SHORT_INT (2^15) : -32768
INTEGER (2^31 -1) = 2147483647
INTEGER (2^31) : -2147483648
LONG_INT (2^63 -1) = 9223372036854775807
LONG_INT (2^63) : -9223372036854775808
</pre>
 
Line 1,449 ⟶ 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>.
<langsyntaxhighlight lang="c">#include <stdio.h></syntaxhighlight>
 
<langsyntaxhighlight lang="lingo">put -(-2147483647-1)
-- -2147483648
 
Line 1,464 ⟶ 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,505 ⟶ 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}}==
Note that some of the UInt64 tests not tested in the code because they raise compile-time errors (alerting the programmer to range errors). The exception text has been included for completeness.
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>.
 
===General behavior regarding overflow===
<lang Nim>import macros, strutils
 
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.
macro toIntVal(s: static[string]): untyped =
result = parseExpr(s)
 
Catching an overflow (when --panics is off) is done this way:
proc `/`(x,y:int64): float = return (x.float / y.float)
<syntaxhighlight lang="nim">try:
var x: int32 = -2147483647
x = -(x - 1) # Raise overflow.
echo x
except OverflowDefect:
echo "Overflow detected"</syntaxhighlight>
 
It is possible to tell the compiler to not generate code to detect overflows by using pragmas “push” and “pop”:
const
<syntaxhighlight lang="nim">{.push overflowChecks: off.}
strInt32 = ["-(-2147483647-1)",
try:
"2_000_000_000 + 2_000_000_000",
var x: int32 = "-2147483647 - 2147483647",
x = -(x - 1)
"46341 * 46341",
echo x # -2147483648 — Wrong result as 2147483648 doesn't fit in an int32.
"(-2147483647-1) / -1"]
except OverflowDefect:
shouldBInt32 = ["2147483648",
echo "Overflow detected" # Not "4000000000",executed.
{.pop.}</syntaxhighlight>
"-4294967294",
"2147488281",
"2147483648"]
strInt64 = ["-(-9_223372_036854_775807-1) ",
"5_000000_000000_000000+5_000000_000000_000000",
"-9_223372_036854_775807 - 9_223372_036854_775807",
"3037_000500 * 3037_000500",
"(-9_223372_036854_775807-1) / -1"]
shouldBInt64 = ["9223372036854775808",
"10000000000000000000",
"-18446744073709551614",
"9223372037000250000",
"9223372036854775808"]
strUInt32 = ["-4294967295",
"3000_000000 +% 3000_000000",
"2147483647 -% 4294967295",
"65537 *% 65537"]
shouldBUInt32 = ["-4294967295",
"6000000000",
"-2147483648",
"4295098369"]
strUInt64 = ["-18446744073709551615",
"10_000000_000000_000000 +% 10_000000_000000_000000",
"9_223372_036854_775807 -% 18_446744_073709_551615",
"4294967296 * 4294967296",
"4294967296 *% 4294967296",] # testing * and *%
shouldBUInt64 = ["-18446744073709551615",
"20000000000000000000",
"-9223372036854775808",
"18446744073709551616",
"18446744073709551616"]
#
# use compile time macro to convert string expr to numeric value
#
var
resInt32: seq[string] = @[$toIntVal(strInt32[0]),
$toIntVal(strInt32[1]),
$toIntVal(strInt32[2]),
$toIntVal(strInt32[3]),
$toIntVal(strInt32[4])]
 
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.
resInt64: seq[string] = @[$toIntVal(strInt64[0]),
$toIntVal(strInt64[1]),
$toIntVal(strInt64[2]),
$toIntVal(strInt64[3]),
$toIntVal(strInt64[4])]
 
For unsigned integers, Nim doesn’t check for overflow but uses modular arithmetic.
resUInt32: seq[string] = @[$toIntVal(strUInt32[0]),
$toIntVal(strUInt32[1]),
$toIntVal(strUInt32[2]),
$toIntVal(strUInt32[3])]
 
===Program to check behavior when overflow is not detected===
resUInt64: seq[string] = @["18446744073709551615 out of valid range",
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.
"10_000000_000000_000000 out of valid range",
"18_446744_073709_551615 out of valid range",
$toIntVal(strUInt64[3]),
$toIntVal(strUInt64[4])]
 
<syntaxhighlight lang="nim">echo "For 32 bits signed integers with overflow check suppressed:"
proc main() =
{.push overflowChecks: off.}
# output format:
var a: int32
#
a = -(-2147483647i32 - 1'i32)
# stringExpr -> calculatedValueAsAString (expectedValueAsAString)
echo " -(-2147483647-1) gives ", a # -2147483648.
echo "-- INT32 --"
a = 2000000000i32 + 2000000000i32
for i in 0..<resInt32.len:
echo " 2000000000 + 2000000000 gives ", a # -294967296.
echo align(strInt32[i], 35), " -> ", align($resInt32[i], 15), " (", $shouldBInt32[i],")"
a = -2147483647i32 - 2147483647i32
echo " -2147483647 - 2147483647 gives ", a # 2.
a = 46341i32 * 46341i32
echo " 46341 * 46341 gives ", a # -2147479015.
a = (-2147483647i32 - 1i32) div -1i32
echo " (-2147483647-1) / -1 gives ", a # -2147483648.
{.pop.}
echo ""
 
echo "For 64 bits signed integers with overflow check suppressed:"
echo "-- INT64 --"
{.push overflowChecks: off.}
for i in 0..<resInt64.len:
var b: int64
echo align(strInt64[i], 55), " -> ", align($resInt64[i], 25), " (", $shouldBInt64[i],")"
b = -(-9223372036854775807i64 - 1i64)
echo " -(-9223372036854775807-1) gives ", b # -9223372036854775808.
b = 5000000000000000000i64 + 5000000000000000000i64
echo " 5000000000000000000 + 5000000000000000000 gives ", b # -8446744073709551616.
b = -9223372036854775807i64 - 9223372036854775807i64
echo " -9223372036854775807 - 9223372036854775807 gives ", b # 2.
b = 3037000500i64 * 3037000500i64
echo " 3037000500 * 3037000500 gives ", b # -9223372036709301616.
b = (-9223372036854775807i64 - 1i64) div -1i64
echo " (-9223372036854775807-1) / -1 gives ", b # -9223372036854775808.
{.pop.}
echo ""
 
echo "--For 32 bits UINT32unsigned --integers:"
var c: uint32
for i in 0..<resUInt32.len:
echo " -4294967295 doesn’t compile."
echo align(strUInt32[i], 35), " -> ", align($resUInt32[i], 20), " (", $shouldBUInt32[i],")"
c = 3000000000u32 + 3000000000u32
echo " 3000000000 + 3000000000 gives ", c # 1705032704.
c = 2147483647u32 - 4294967295u32
echo " 2147483647 - 4294967295 gives ", c # 2147483648.
c = 65537u32 * 65537u32
echo " 65537 * 65537 gives ", c # 131073.
echo ""
 
echo "--For 64 bits UINT64unsigned --integers:"
var d: uint64
for i in 0..<resUInt64.len:
echo " -18446744073709551615 doesn’t compile."
echo align(strUInt64[i], 55), " -> ", align($resUInt64[i], 42), " (", $shouldBUInt64[i],")"
d = 10000000000000000000u64 + 10000000000000000000u64
echo " 10000000000000000000 + 10000000000000000000 gives ", d # 1553255926290448384.
d = 9223372036854775807u64 - 18446744073709551615u64
echo " 9223372036854775807 - 18446744073709551615 gives ", d # 9223372036854775808.
d = 4294967296u64 * 4294967296u64
echo " 4294967296 * 4294967296 gives ", d # 0.</syntaxhighlight>
 
main()
</lang>
{{out}}
<pre>For 32 bits signed integers with overflow check suppressed:
<pre>-- INT32 --
-(-2147483647-1) gives -> 2147483648 (2147483648)
2000000000 + 2000000000 gives -294967296
2_000_000_000 + 2_000_000_000 -> 4000000000 (4000000000)
-2147483647 - 2147483647 ->gives -4294967294 (-4294967294)2
46341 * 46341 gives -> 2147488281 (2147488281)2147479015
(-2147483647-1) / -1 gives -> 2147483648.0 (2147483648)
 
-- INT64 --
For 64 bits signed integers with overflow check suppressed:
-(-9_223372_036854_775807-1) -> -9223372036854775808 (9223372036854775808)
-(-9223372036854775807-1) gives -9223372036854775808
5_000000_000000_000000+5_000000_000000_000000 -> 9223372036854775807 (10000000000000000000)
5000000000000000000 + 5000000000000000000 gives -8446744073709551616
-9_223372_036854_775807 - 9_223372_036854_775807 -> -9223372036854775808 (-18446744073709551614)
-9223372036854775807 - 9223372036854775807 gives 2
3037_000500 * 3037_000500 -> 9223372036854775807 (9223372037000250000)
3037000500 * 3037000500 gives -9223372036709301616
(-9_223372_036854_775807-1) / -1 -> 9.223372036854776e+018 (9223372036854775808)
(-9223372036854775807-1) / -1 gives -9223372036854775808
-- UINT32 --
 
-4294967295 -> -4294967295 (-4294967295)
For 32 bits unsigned integers:
3000_000000 +% 3000_000000 -> 6000000000 (6000000000)
-4294967295 doesn’t compile.
2147483647 -% 4294967295 -> -2147483648 (-2147483648)
3000000000 + 3000000000 gives 1705032704
65537 *% 65537 -> 4295098369 (4295098369)
2147483647 - 4294967295 gives 2147483648
-- UINT64 --
65537 * 65537 gives 131073
-18446744073709551615 -> 18446744073709551615 out of valid range (-18446744073709551615)
 
10_000000_000000_000000 +% 10_000000_000000_000000 -> 10_000000_000000_000000 out of valid range (20000000000000000000)
For 64 bits unsigned integers:
9_223372_036854_775807 -% 18_446744_073709_551615 -> 18_446744_073709_551615 out of valid range (-9223372036854775808)
-18446744073709551615 doesn’t compile.
4294967296 * 4294967296 -> 9223372036854775807 (18446744073709551616)
10000000000000000000 + 10000000000000000000 gives 1553255926290448384
4294967296 *% 4294967296 -> 0 (18446744073709551616)
9223372036854775807 - 18446744073709551615 gives 9223372036854775808
</pre>
4294967296 * 4294967296 gives 0</pre>
 
=={{header|Oforth}}==
Line 1,648 ⟶ 2,128:
 
=={{header|PARI/GP}}==
Although it appears at a glance that GP offers only <code>t_INT</code> (unlimited precision) integers, in fact machineMachine-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,659 ⟶ 2,139:
 
Of course PARI can use the same techniques as [[#C|C]].
 
Additionally, you can, in principle, overflow a <code>t_INT</code>. The length, in words, of a <code>t_INT</code> is given in a single word. Hence on 32 bit a <code>t_INT</code> cannot have more than 2^32-1 words, limiting it to the range
:<math>\{-(2^{2^{32}-1}-1), -(2^{2^{32}-1}-2), \ldots, -2, -1, 0, 1, 2, \ldots, 2^{2^{32}-1}-2, 2^{2^{32}-1}-1\}</math>
or
:<math>\{-(2^{2^{64}-1}-1), -(2^{2^{64}-1}-2), \ldots, -2, -1, 0, 1, 2, \ldots, 2^{2^{64}-1}-2, 2^{2^{64}-1}-1\}</math>
with 64-bit.
 
(Note that these bounds are different from an IEEE 754-style floating point because the sign bit is stored externally.) It takes > 18 exabytes to overflow a <code>t_INT</code> on 64-bit (roughly Google's total storage as of 2014), but it's doable in 32-bit. Has anyone tried? I imagine you'd get a memory error or the like.
 
=={{header|Perl}}==
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>.
<langsyntaxhighlight lang="c">#include <stdio.h></syntaxhighlight>
 
<langsyntaxhighlight lang="perl">
use strict;
use warnings;
Line 1,677 ⟶ 2,165:
say(3037000500 * 3037000500);
say((-9223372036854775807-1) / -1);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,689 ⟶ 2,177:
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Phix has both 32 and 64 bit implementations. Integers are signed and limited to 31 (or 63) bits, ie
-1,073,741,824 to +1,073,741,823 (-#40000000 to #3FFFFFFF) on 32 bit, whereas on
Line 1,694 ⟶ 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:
<!--<syntaxhighlight lang="phix">-->
<lang Phix>integer i = 1000000000 + 1000000000</lang>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
Line 1,701 ⟶ 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,708 ⟶ 2,201:
=={{header|Pike}}==
Pike transparently promotes int to bignum when needed, so integer overflows do not occur.
 
=={{header|PL/M}}==
{{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>.
<syntaxhighlight lang="pli">100H: /* SHOW INTEGER OVERFLOW */
 
/* CP/M SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* CONSOLE I/O ROUTINES */
PRCHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END;
PRNUMBER: PROCEDURE( N );
DECLARE N ADDRESS;
DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE;
N$STR( W := LAST( N$STR ) ) = '$';
N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 );
DO WHILE( ( V := V / 10 ) > 0 );
N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
END;
CALL PRSTRING( .N$STR( W ) );
END PRNUMBER;
 
/* TASK */
 
/* THE ONLY TYPES SUPPORTED BY THE ORIGINAL PL/M COMPILER ARE */
/* UNSIGED, BYTE IS 8 BITS AND ADDRESS IS 16 BITS */
DECLARE SV BYTE, LV ADDRESS;
 
SV = 255; /* MAXIMUM BYTE VALUE */
LV = 65535; /* MAXIMUM ADDRESS VALUE */
 
CALL PRSTRING( .'8-BIT: $' );
CALL PRNUMBER( SV );
CALL PRSTRING( .' INCREMENTS TO: $' );
SV = SV + 1;
CALL PRNUMBER( SV );
CALL PRNL;
 
CALL PRSTRING( .'16-BIT: $' );
CALL PRNUMBER( LV );
CALL PRSTRING( .' INCREMENTS TO: $' );
LV = LV + 1;
CALL PRNUMBER( LV );
CALL PRNL;
 
EOF</syntaxhighlight>
{{out}}
<pre>
8-BIT: 255 INCREMENTS TO: 0
16-BIT: 65535 INCREMENTS TO: 0
</pre>
 
=={{header|PowerShell}}==
Line 1,714 ⟶ 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 1,745 ⟶ 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 1,804 ⟶ 2,349:
say("Quad",q1,q2,SizeOf(q1))
 
Input()</langsyntaxhighlight>
{{out}}
<pre>
Line 1,822 ⟶ 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 1,839 ⟶ 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 1,860 ⟶ 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.
 
=={{header|Quackery}}==
 
Quackery only supports bignums.
 
=={{header|Racket}}==
Line 1,871 ⟶ 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 1,890 ⟶ 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 1,899 ⟶ 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 1,916 ⟶ 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 1,931 ⟶ 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 1,942 ⟶ 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 1,950 ⟶ 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 1,958 ⟶ 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 1,984 ⟶ 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 1,998 ⟶ 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,012 ⟶ 2,578:
<br>
 
<syntaxhighlight lang="rust">
<lang Rust>
// The following will never panic!
println!("{:?}", 65_537u32.checked_mul(65_537)); // None
Line 2,022 ⟶ 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,029 ⟶ 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,043 ⟶ 2,609:
println("Test - Expect Undetected overflow:")
requireOverflow(++(1,1)) // Undetected overflow
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
Line 2,049 ⟶ 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,067 ⟶ 2,633:
writeResult(3037000500 * 3037000500);
writeResult((-9223372036854775807-1) div -1);
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,081 ⟶ 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,091 ⟶ 2,657:
9223372036854775808
</pre>
 
=={{header|Smalltalk}}==
Smalltalk has unlimited precision integers.
However, to emulate wrong behavior (eg. when interfacing to external programs or document formats), it can be emulated.
{{works with|Smalltalk/X}}
<syntaxhighlight lang="smalltalk">2147483647 + 1. -> 2147483648
2147483647 add_32: 1 -> -2147483648
4294967295 + 1. -> 4294967296
16rFFFFFFFF add_32u: 1. -> 0
... simular stuff for sub32/mul32 ...</syntaxhighlight>
 
=={{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,144 ⟶ 2,720:
println(uInt64)
uInt64 = 4294967296 &* 4294967296
println(uInt64)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,176 ⟶ 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,186 ⟶ 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,202 ⟶ 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,215 ⟶ 2,806:
i1=1000000000000000-1 '1E+15-1
i2=i1+1 '1E+15
wscript.echo Cstr(i1) & " , " & Cstr(i2)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,229 ⟶ 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,241 ⟶ 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,255 ⟶ 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,271 ⟶ 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,283 ⟶ 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,348 ⟶ 2,939:
Catch ex As Exception
Debug.Print("Exception raised : " & ex.Message)
End Try</langsyntaxhighlight>
{{out}}
<pre>
Line 2,361 ⟶ 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,381 ⟶ 2,972:
continues with wrong results.
 
<langsyntaxhighlight XPL0lang="xpl0">int N;
[N:= -(-2147483647-1);
IntOut(0, N); CrLf(0);
Line 2,392 ⟶ 2,983:
N:= (-2147483647-1)/-1;
IntOut(0, N); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,402 ⟶ 2,993:
-2147483648
</pre>
 
=={{header|Z80 Assembly}}==
===Zilog Z80===
The <code>P</code> flag represents overflow after an arithmetic operation, and bit parity after a bitwise or logical operation. Arithmetic operations will result in overflow if the 0x7F-0x80 boundary is crossed (or in the case of 16-bit math, the 0x7FFF-0x8000 boundary.) One quirk of the Z80 instruction set is that program counter relative jumps cannot be done based on overflow; only calls, returns, and jumps to fixed memory locations are allowed. In other words, the instructions <code>JR PE, label</code> and <code>JR PO, label</code> <i>do not exist.</i>
 
There are no assembler mnemonics for overflow specifically, so we must borrow the ones for parity.
Your assembler may have overflow mnemonics but it's not a standard feature of the language.
* <code>PE</code> parity even, overflow occurred.
* <code>PO</code> parity odd, no overflow
 
<syntaxhighlight lang="z80">ld a,&7F
add 1
jp pe,ErrorHandler ;pe = parity even, but in this case it represents overflow set</syntaxhighlight>
 
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.'''
 
===Game Boy===
The Game Boy's CPU has no parity/overflow flag, and therefore all control flow structures related to it have been removed. Overflow can still be detected in theory, but it's a difficult process that requires the exclusive or of the carry flag and whether a subtraction changed the sign of the accumulator or not. Since the Game Boy's CPU cannot natively detect overflow, the CPU <b> will continue with a wrong result.</b>
 
=={{header|zkl}}==
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