Types and Literals

Preventing Number Overflow

How can I check if my number will cause an overflow before performing a calculation?

3D art representing computer programming

Preventing overflow is important, especially in programs where accuracy is crucial. Here are some ways to check for potential overflow before it happens:

Check Against Type Limits

C++ provides constants that tell us the maximum and minimum values for each number type. We can check against these before doing calculations:

#include <iostream>
#include <limits>
using namespace std;

int main() {
  int PlayerGold{2'000'000'000};  // 2 billion
  int GoldToAdd{500'000'000};     // 500 million

  // Check if adding would exceed the maximum
  if (PlayerGold >
    numeric_limits<int>::max() - GoldToAdd) {
    cout << "Warning: Adding this much gold"
      " would overflow!\n";
  } else {
    PlayerGold += GoldToAdd;
    cout << "New gold amount: "
      << PlayerGold << '\n';
  }

  // Let's try with a smaller amount
  GoldToAdd = 100'000'000;  // 100 million

  if (PlayerGold >
    numeric_limits<int>::max() - GoldToAdd) {
    cout << "Warning: Adding this much gold"
      " would overflow!\n";
  } else {
    PlayerGold += GoldToAdd;
    cout << "New gold amount: " << PlayerGold;
  }
}
Warning: Adding this much gold would overflow!
New gold amount: 2100000000

Use Bigger Types When Needed

If you're working with values that might get very large, use a bigger type from the start:

#include <iostream>
using namespace std;

int main() {
  // This might overflow:
  int32_t Score{2'000'000'000};
  Score *= 2;  
  cout << "Score (might overflow): " << Score;

  // This is safe:
  int64_t BigScore{2'000'000'000};
  BigScore *= 2;
  cout << "\nBigScore (safe): " << BigScore;
}
Score (might overflow): -294967296
BigScore (safe): 4000000000

Set Reasonable Limits

Often, the best approach is to set reasonable limits on your values:

#include <iostream>
using namespace std;

int main() {
  int PlayerHealth{100};
  int HealthPotion{50};
  int MaxHealth{100};

  // Check if healing would exceed max health
  if (PlayerHealth + HealthPotion > MaxHealth) {
    PlayerHealth = MaxHealth;
    cout << "Health restored to maximum: "
      << PlayerHealth << '\n';
  } else {
    PlayerHealth += HealthPotion;
    cout << "Health increased to: "
      << PlayerHealth;
  }
}
Health restored to maximum: 100

Remember:

  • Always check for overflow when working with critical calculations
  • Use appropriate type sizes for your data
  • Set reasonable limits where possible
  • Consider using larger types if you need to work with very large numbers
  • When in doubt, test with extreme values to make sure your program handles them correctly
This Question is from the Lesson:

Types and Literals

Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

Types and Literals

Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 60 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved