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 :
// 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 ?