Narrowing Conversions
What is narrowing conversion
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 compiler 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}; // Compile will show error ! uniform initialization don't allow narrowing conversion.