What is Narrowing Conversion in C++?

date
Mar 5, 2023
slug
narrowing-conversion
status
Published
tags
CPP
summary
Narrowing conversion is a type of type conversion in C++ where a value of a larger data type is converted to a value of a smaller data type, resulting in loss of information.
type
Post
Narrowing conversion is a type of type conversion in C++ where a value of a larger data type is converted to a value of a smaller data type, resulting in loss of information. In other words, narrowing conversion is when a value is converted to a type that cannot accurately represent the original value.
For example, if you have a floating-point number with a decimal value of 3.14159 and you want to convert it to an integer, the decimal value will be lost, resulting in the integer value 3. This is a narrowing conversion because the original value cannot be accurately represented in the smaller data type.
Example 1: Converting from a double to an int (implicitly)
double x = 3.14159;
int y = x; // This is a narrowing conversion and will result in loss of precision
std::cout << y << std::endl; // Output: 3
Narrowing conversions are not allowed implicitly in C++. They can only be done explicitly with a cast operator. If a narrowing conversion is attempted implicitly, the compiler will issue a warning or error message to alert the programmer.
Example 2: Using an explicit cast to perform a narrowing conversion (explicit)
double x = 3.14159;
int y = static_cast<int>(x); // This is a narrowing conversion performed explicitly
std::cout << y << std::endl; // Output: 3
It's important to be aware of narrowing conversions because they can result in unexpected behavior or loss of precision in your code. Therefore, it's a good practice to avoid them whenever possible and to always explicitly cast values when necessary.

© therainisme 2025