Yes! There are several ways to make your code more strict about type conversions. Let's look at the main approaches:
The simplest way to catch many unwanted conversions is to always use { }
for initialization instead of =
:
int main() {
// These dangerous conversions are caught:
int MyInt{3.14};
// Compiles but loses data:
int UnsafeInt = 3.14;
}
error C2397: conversion from 'double' to 'int' requires a narrowing conversion
Modern C++ compilers can warn you about implicit conversions. Here's how they help:
#include <iostream>
using namespace std;
int main() {
double Pi{3.14159};
// The compiler will warn about these:
int RoundedPi = Pi;
bool IsPositive = Pi;
cout << RoundedPi << "\n";
cout << std::boolalpha << IsPositive;
}
3
true
Most compilers will show warnings for these lines, helping you catch potential problems.
When you do need to convert between types, you can make your intentions clear using static_cast<>()
:
#include <iostream>
using namespace std;
int main() {
double Pi{3.14159};
// These make our intentions clear:
int RoundedPi{static_cast<int>(Pi)};
bool IsPositive{static_cast<bool>(Pi)};
cout << "Rounded: " << RoundedPi << "\n";
cout << "Is Positive: " << std::boolalpha
<< IsPositive;
}
Rounded: 3
Is Positive: true
Here are some tips to help prevent unwanted conversions:
{ }
static_cast<>()
when you really need to convert typesAnswers to questions are automatically generated and may not have been reviewed.
Going into more depth on what is happening when a variable is used as a different type