How to check for an integer overflow

Hello, I'm a beginner in programming and studying C++ by 2 months. Today I'm here because I have a problem with an exercise of the book : Programming principles and practice using C++. I wrote a program to calculate the sum of the first N integers (given N and the integers by the user) and now I have to modify it to print an error message if the sum cannot be representable with an int, Here is my code :



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// calculate the sum of the first N integers
int main()
try {

	cout << "Enter the number of values you want to sum : \n";
	int n = -1; 
	cin >> n; 
	if (n < 1) error("Enter just positive value"); 
	
	cout << "Enter some integers : "; 
	vector<int> val; 
	for (int x; cin >> x;)
		val.push_back(x);

	
	if (val.size() < n) error("Too few numbers\n"); 

	int sum = 0; 

	cout << "The sum of the first : " << n << " Numbers ( "; 
	for (int i = 0; i < n; ++i) {
		cout << val[i] << ' '; 
		sum += val[i]; 

	}
	cout << " ) is : " << sum << '\n'; 

}
catch (runtime_error& e) {
	cerr << "runtime error : " << e.what() << '\n'; 
	return 1;

}
catch (...) {
	cerr << "Oops : something went wrong somewhere\n"; 
	return 2; 
}

How would you check if a value is too large to fit an int ? I know that this is called overflow but I don't know how to handle it because the author has never shown me a way to do this. Is there a formula ? I read that I can check if the sum of 2 numbers with same sign gives me a value with opposite sign that's an overflow.
1) As soon as overflow occurs, your program is in invalid state and can do anything. It is imperative to detect overflow before doing actual sum.
2) One way to detect possible overflow is to substract one operand from maximum value given type can hold. If resilt is less than other operand, then overflow will happen. Something like that:
1
2
3
4
5
6
7
int add(int lhs, int rhs)
{
    if(std::numeric_limits<int>::max() - lhs < rhs) {
        throw std::runtime_error("signed overflow has occured");
    }
    return lhs + rhs;
}

3) Code I posted works only if lhs is positive. If it is negative, you should mirror your checks: check if result of substraction of lhs from minimum value of int is larger than other operand. Implementation and check for lhs sign is up to you.
@MiiNiPaa How can I check for an overflow when I read every value in the vector ? In that case I don't have two operands for the check, so what should I do ?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//
#include <iostream>
#include <vector>
#include <string>
 
bool stIsGreater(std::string s1, std::string s2){
	if(s1.size() > s2.size()) return true;
	else if(s1.size() < s2.size()) return false;
	else{
		for(size_t siz=0; siz<s1.size(); siz++){
			if(s1[siz] > s2[siz]) return true;
		}
	}
	return false;
}
 
int main(){
	std::vector<int>vec;
	std::string iMax = std::to_string(INT_MAX);
	std::string ss;
	std::cout << "enter a number: ";
	std::cin >> ss;
	if(stIsGreater(ss, iMax)) std::cout << "greater than int limit";
	else{
		std::cout << "acceptable";
		vec.push_back(stoi(ss));		
	} 
	
}


edit: code could be added for negative values and zeros at the beginning and for non digit inputs.
Last edited on
Topic archived. No new replies allowed.