Detecting Overflow and Truncation in Integers
This lesson explains how overflow and truncation can be detected and prevented.
We'll cover the following
Detecting overflow #
Although detecting overflow uses functions, if conditions and ref parameters, which we have not covered yet, it should be mentioned here that the core.checkedint
module contains arithmetic functions that detect overflow. Instead of operators like +
and -
, this module uses functions: adds
and addu
for signed and unsigned addition, muls
and mulu
for signed and unsigned multiplication, subs
and subu
for signed and unsigned subtraction and negs
for negation.
Example #
Assume that a
and b
are two int variables, the following code can detect if adding them has caused an overflow:
Get hands-on with 1400+ tech skills courses.