When you try to store a number that's too large for an integer type, you'll encounter what's called an "integer overflow". This behavior can be subtle and dangerous because C++ won't automatically prevent it or warn you about it.
First, let's see what the limits are for different integer types:
#include <iostream>
#include <limits>
using namespace std;
int main() {
cout << "Maximum int value: "
<< numeric_limits<int>::max() << "\n";
cout << "Minimum int value: "
<< numeric_limits<int>::min() << "\n";
cout << "Maximum unsigned int value: "
<< numeric_limits<unsigned int>::max();
}
Maximum int value: 2147483647
Minimum int value: -2147483648
Maximum unsigned int value: 4294967295
When overflow occurs, the number "wraps around". Here's what that looks like:
#include <iostream>
using namespace std;
int main() {
int score{2147483647}; // Maximum int value
cout << "Starting score: " << score;
// Overflow occurs here
score += 1;
cout << "\nAfter adding 1: " << score;
// Maximum unsigned int
unsigned int playerCount{4294967295};
cout << "\n\nStarting player count: "
<< playerCount;
// Unsigned overflow
playerCount += 1;
cout << "\nAfter adding 1: " << playerCount;
}
Starting score: 2147483647
After adding 1: -2147483648
Starting player count: 4294967295
After adding 1: 0
Here's a safer way to handle potentially large numbers:
#include <iostream>
#include <limits>
using namespace std;
bool addScoreSafely(
int& currentScore, int pointsToAdd) {
// Check if addition would cause overflow
if (pointsToAdd > 0 &&
currentScore > numeric_limits<int>::max()
- pointsToAdd) {
cout << "Warning: Adding " << pointsToAdd
<< " would cause overflow!\n";
return false;
}
// Check if subtraction would cause overflow
if (pointsToAdd < 0 &&
currentScore < numeric_limits<int>::min()
- pointsToAdd) {
cout << "Warning: Adding " << pointsToAdd
<< " would cause underflow!\n";
return false;
}
currentScore += pointsToAdd;
return true;
}
int main() {
int score{2147483640};
cout << "Current score: " << score << "\n";
// Try to add 5 points
if (addScoreSafely(score, 5)) {
cout << "Successfully added 5 points. "
"New score: " << score << "\n";
}
// Try to add 10 more points (would overflow)
addScoreSafely(score, 10);
}
Current score: 2147483640
Successfully added 5 points. New score: 2147483645
Warning: Adding 10 would cause overflow!
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the different types of numbers in C++, and how we can do basic math operations on them.