Implicit Conversions and Narrowing Casts

Testing Type Conversions

Is there a way to check what value a type will be converted to before using it?

3D art showing a wizard character

Yes! The easiest way to check how a value will be converted is to create a small test program. Let's look at how to do this safely:

#include <iostream>
using namespace std;

int main() {
  // Store the original value in a variable
  double Original{3.7};

  // Then create new variable of the target type
  int Converted{static_cast<int>(Original)};

  // Print both to see the difference
  cout << "Original value: " << Original;
  cout << "\nConverted value: " << Converted;
}
Original value: 3.7
Converted value: 3

We can do the same thing with other types too. Here's how different number types convert to bool:

#include <iostream>
using namespace std;

int main() {
  int Zero{0};
  int One{1};
  int FortyTwo{42};

  bool FromZero{static_cast<bool>(Zero)};
  bool FromOne{static_cast<bool>(One)};
  bool FromFortyTwo{static_cast<bool>(FortyTwo)};

  // Makes cout show "true"/"false"
  cout << std::boolalpha;
  cout << "0 converts to: " << FromZero << "\n";
  cout << "1 converts to: " << FromOne << "\n";
  cout << "42 converts to: " << FromFortyTwo;
}
0 converts to: false
1 converts to: true
42 converts to: true

Notice we used static_cast<>() in these examples. This is the safe way to do conversions in C++. While implicit conversions will work too, using static_cast<>() makes it clear to other programmers (and yourself!) that you intended to do the conversion.

Remember that some conversions might lose data (like when converting from double to int), so it's always good to test your conversions with realistic values before using them in your actual program.

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