The Program in C++ to Check Overflow/Underflow during various arithmetical operations is given below:
Here’s an example of a C++ program that checks for overflow/underflow during addition:
#include <iostream>
#include <climits>
using namespace std;
int main() {
int a, b;
// Input two numbers
cout << "Enter two numbers: ";
cin >> a >> b;
// Check for overflow
if (a > INT_MAX - b) {
cout << "Overflow Occured" << endl;
}
// Check for underflow
else if (a < INT_MIN - b) {
cout << "Underflow Occured" << endl;
}
// No overflow/underflow
else {
cout << "The sum is: " << a + b << endl;
}
return 0;
}
Output:
Enter two numbers: 4
7
Underflow Occured
Enter two numbers: 6
3
The product is: 18
You can check for overflow/underflow in other arithmetic operations in a similar way.
Pro-Tips💡
For example, to check for overflow/underflow during multiplication, you can use 'INT_MAX / b'
and ‘INT_MIN / b
‘ to check for overflow/underflow, respectively.
#include <iostream>
#include <climits>
using namespace std;
int main() {
int a, b;
// Input two numbers
cout << "Enter two numbers: ";
cin >> a >> b;
// Check for overflow
if (b != 0 && a > INT_MAX / b) {
cout << "Overflow Occured" << endl;
}
// Check for underflow
else if (b != 0 && a < INT_MIN / b) {
cout << "Underflow Occured" << endl;
}
// No overflow/underflow
else {
cout << "The product is: " << a * b << endl;
}
return 0;
}
Note that the above code is checking for overflow and underflow on integer arithmetic operations.
If you want to check for these conditions on floating point numbers,
you will have to use different techniques, such as comparing against the INFINITY
and -INFINITY
values.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.