Disabling Implicit Conversions
Can I prevent the compiler from doing any implicit conversions in my code?
Yes! There are several ways to make your code more strict about type conversions. Let's look at the main approaches:
Using Uniform Initialization
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
Using Compiler Warnings
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.
Using explicit Casts
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
Good Practices for Preventing Unwanted Conversions
Here are some tips to help prevent unwanted conversions:
- Always use uniform initialization with
{ }
- Enable compiler warnings (your IDE probably has these on by default)
- Use
static_cast<>()
when you really need to convert types - Review compiler warnings regularly - don't ignore them!
- Pick the right types for your data from the start
Implicit Conversions and Narrowing Casts
Going into more depth on what is happening when a variable is used as a different type