Tech Tip: Safe Signed 32-Bit Integer Addition with Wraparound
PRODUCT: 4D | VERSION: 21 | PLATFORM: Mac & Win
Published On: December 4, 2025
when maintaining a high-volume counter (e.g., sequence IDs, hash values, or loop iterators) stored in an Integer variable. Incrementing beyond MAXLONG (2147483647) with $counter += 1 triggers signed integer overflow, leading to undefined behavior. Results vary by platform (Windows/macOS), CPU (Intel/ARM), and mode (interpreted/compiled), causing bugs like incorrect comparisons or crashes. Direct arithmetic in conditions (e.g., ($b - $a) >= 0) can also overflow inconsistently.
Utility Method: util_wrapping
Test Example:
Utility Method: util_wrapping
| #DECLARE($a : Integer; $b : Integer)->$result : Integer var $modulo; $minInt; $maxInt : Real $modulo:=4294967296 $minInt:=-2147483648 $maxInt:=2147483647 var $realA; $realB; $realC : Real $realA:=$a $realB:=$b $realC:=$realA+$realB Case of : ($realC>$maxInt) $realC-=$modulo OK:=0 : ($realC<$minInt) $realC+=$modulo OK:=0 Else OK:=1 End case $result:=$realC |
Test Example:
| var $a; $b; $result : Integer var $r : Boolean $a:=MAXLONG // 2147483647 $b:=util_wrapping($a; 1) $result:=util_wrapping($b; -1) $r:=($b>=$a) If (OK=1) ALERT("No overflow in last add") Else ALERT("Overflow detected and wrapped") End if |