Converting Large Numbers
What happens if I try to convert a really big number to a smaller type?
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!
Implicit Conversions and Narrowing Casts
Going into more depth on what is happening when a variable is used as a different type