Implicit Conversions and Narrowing Casts

Converting Large Numbers

What happens if I try to convert a really big number to a smaller type?

3D art showing a wizard character

When you try to convert a number that's too big for its destination type, you can run into problems. Let's look at some examples to understand what happens:

#include <iostream>
using namespace std;

int main() {
  // A really big number
  long long BigNumber{12345678901234};

  // Try to convert it to a regular int
  int SmallNumber{static_cast<int>(BigNumber)};  

  cout << "Original number: " << BigNumber;
  cout << "\nConverted number: " << SmallNumber;
}
Original number: 12345678901234
Converted number: 1942892530

When you run this program, you might get unexpected results - the number might be completely different from what you put in! This is called overflow, and it happens because different number types can hold different ranges of values.

Here's another example with decimal numbers:

#include <iostream>
using namespace std;

int main() {
  // A float can't hold as many decimal places
  // as a double
  double Precise{123456789.123456789};
  float LessPrecise{static_cast<float>(Precise)};  

  // Show more decimal places
  cout.precision(12);
  cout << "Original number: " << Precise;
  cout << "\nConverted number: " << LessPrecise;
}
Original number: 123456789.123
Converted number: 123456792

Notice how we lost some precision in the decimal places! This is because float can't store as many digits as double.

To avoid these problems, you should:

  • Use types that are big enough for your numbers
  • Test your conversions with the actual values you'll be using
  • Use uniform initialization with { } instead of = when possible, as it will warn you about dangerous conversions
  • Consider whether you really need to convert between types at all

Remember: just because C++ lets you convert between types doesn't always mean you should!

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

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