liveBook · Manning

Narrowing conversion

As explained in Modern C, Third Edition

A narrowing conversion is a conversion to a type that represents a smaller range or less precise set of values than the source type.

A narrowing conversion changes a value to a type with a smaller range or less precision. The conversion is harmless when the value fits, but it can produce implementation-dependent danger or information loss when it does not. Decimal and hexadecimal literals can behave differently: -2'147'483'648 fits a signed int, while -0x8000'0000 can represent an out-of-range value before negation. Unsigned conversion uses modular arithmetic, so converting 0x8000'0000 to unsigned short can produce 0. TAKEAWAY: avoid narrowing conversions and avoid narrow types in arithmetic. section 5.4

double         a =  1;             // Harmless; value fits type
signed short   b = -1;             // Harmless; value fits type
signed int     c =  0x8000'0000;   // Dangerous; value too big for type
signed int     d = -0x8000'0000;   // Dangerous; value too big for type
signed int     e = -2'147'483'648; // Harmless; value fits type
unsigned short g =  0x8000'0000;   // Loses information; has value 0

Compare harmless conversions with out-of-range signed values and an unsigned conversion that loses information. section 5.4

How Modern C, Third Edition covers it

How deep it goes
Explains value-fit checks, literal-specific behavior, unsigned modular conversion, and precision loss in mixed arithmetic.
Examples
Uses signed and unsigned assignments, hexadecimal and decimal minimum values, and mixed integer-floating-point expressions.
What it assumes
Assumes familiarity with C literals, integer types, arithmetic, and signed versus unsigned values.
What you can do after
Evaluate whether conversions preserve values and identify cases that may lose range, precision, or information.
How it connects
Connects narrowing conversion with integer types, literals, arithmetic operators, floating-point types, precision, and signedness.

Also explained in

Compare how 3 books explain narrowing conversion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.