Narrowing Conversions

Narrowing conversion is a conversion of a value including the loss of it's precision. Most of the times that is not what you want. [1]


The compile can not determine if the specified value fits in the new field that you assign it to. If you are sure that there is no overflow, explicitly type cast the value to avoid the warning.

Below shows the level of narrowing conversion of data lossness.

long double > double > float > long > int > short > char

double d = 7.9;
int i = d; // bad, narrowing i becomes 7
i = (int) d; // bad, not explicit enough

void f(int x, long y, double d) {
	char c1 = x; // bad, narrowing
	char c2 = y; // bad, narrowing
	char c3 = z; // bad, narrowing
}

How to Avoid Narrowing Conversion

Since C++11, uniform initialization prohibits narrowing conversion by using braces. For example:

double x, y, z;
int sum1 = x + y + z; // Causion ! Narrowing conversion by assignment
int sum1{x+y+z}; // Error ! uniform initialization don't allow narrowing conversion.

  1. https://www.modernescpp.com/index.php/c-core-guidelines-rules-for-conversions-and-casts ↩︎

  2. https://www.ibm.com/docs/en/ztpf/2020?topic=warnings-narrowing-conversion ↩︎