![]() |
VOOZH | about |
In C++, unsigned integer is a datatype that can store only zero and non-negative integer values. According to C++ standard, unsigned integer overflow is defined behavior (as it wraps around using modulo arithmetic and starts again from 0). So, to detect when this wrapping occurred is important to detect the overflow. In this article, we will learn how to detect unsigned integer overflow in C++.
The most simple and efficient method to detect the unsigned integer overflow is to check for overflow before performing an arithmetic operation. This involves comparing the operands against the maximum value that the type can hold before performing the operation.
b) is greater than the maximum value minus the first operand (a). If true, then adding a and b will definitely overflow.a) is greater than the maximum value divided by the second operand (b) (given b is not zero). If true, a * b will overflow.Note: When an overflow occurs, the value of the unsigned integer is reset to zero and the higher bits are lost.
The following program illustrates how we can detect unsigned integer overflow in C++.
Addition overflow will occur! Multiplication overflow will occur!
Time Complexity: O(1)
Auxiliary Space: O(1)