Implicit Conversions and Narrowing Casts

Disabling Implicit Conversions

Can I prevent the compiler from doing any implicit conversions in my code?

3D art showing a wizard character

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

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