Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between narrowing and truncation in C++?

I've been going through a book (C++ Programming Language Stroustrup 4th ed). An example given in a section related to Initialization as below:

void f(double d, int i)
{
    int a{ d };     // error : possible truncation
    char b{ i };    // error : possible narrowing
}

What exactly is the difference between truncation and narrowing?

like image 455
pasha Avatar asked Dec 23 '22 18:12

pasha


1 Answers

A narrowing conversion is basically any conversion that may cause a loss of information. Strictly speaking, a narrowing conversion is :

an implicit conversion

  • from a floating-point type to an integer type, or
  • from long double to double or float, or from double to float, except where the source is a constant expression and the actual value after conversion is within the range of values that can be represented (even if it cannot be represented exactly), or
  • from an integer type or unscoped enumeration type to a floating-point type, except where the source is a constant expression and the actual value after conversion will fit into the target type and will produce the original value when converted back to the original type, or
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where the source is a constant expression whose value after integral promotions will fit into the target type, or
  • from a pointer type or a pointer-to-member type to bool.

Notice that this means both of the conversions you posted are narrowing conversion. int a{ d }; is the first case and char b{ i }; is the fourth.

Truncation only occurs when converting between a floating point type and an integer type. It generally refers to the decimal portion of the floating point number being lost (source). This implies that truncation is a subset of narrowing conversions.

like image 187
François Andrieux Avatar answered Jan 13 '23 21:01

François Andrieux