liveBook · Manning

Narrowing conversion

As explained in Modern C

A narrowing conversion is a conversion to a type whose representable range or precision cannot preserve all values of the source type.

A narrowing conversion changes a value to a type that cannot preserve its full range or precision. The result may be harmless when the value fits, but it may lose information or produce a surprising value when it does not. section 5.4

double          a = 1;             // Harmless; value fits type
signed short    b = -1;            // Harmless; value fits type
signed int      c = 0x80000000;    // Dangerous; value too big for type
signed int      d = -0x80000000;   // Dangerous; value too big for type
signed int      e = -2147483648;   // Harmless; value fits type
unsigned short  g = 0x80000000;    // Loses information; has value 0


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":0},{\"line\":0,\"ch\":6}],[{\"line\":1,\"ch\":0},{\"line\":1,\"ch\":12}],[{\"line\":5,\"ch\":2},{\"line\":5,\"ch\":14}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":10}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":10}],[{\"line\":4,\"ch\":0},{\"line\":4,\"ch\":10}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":10}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":10}],[{\"line\":4,\"ch\":0},{\"line\":4,\"ch\":10}],[{\"line\":2,\"ch\":0},{\"line\":2,\"ch\":10}],[{\"line\":3,\"ch\":0},{\"line\":3,\"ch\":10}],[{\"line\":4,\"ch\":0},{\"line\":4,\"ch\":10}],[{\"line\":5,\"ch\":0},{\"line\":5,\"ch\":14}]]"}
!@%STYLE%@!

Compare assignments that preserve values with assignments that exceed the destination type. The unsigned-short example loses information and produces zero under the stated modulus assumption. section 5.4

TAKEAWAY

  • Avoid narrowing conversions when the destination type may not represent the source value. section 5.4
  • Do not use narrow types in arithmetic; mixed operands can also lose range or precision. section 5.4

How Modern C covers it

How deep it goes
Explains fitting values, overflow-related results, precision loss, and mixed signedness, but defers broader type-rule details.
Examples
Uses integer assignments, floating-point expressions, and signed-versus-unsigned comparisons to expose harmless and dangerous conversions.
What it assumes
Assumes familiarity with C values and basic types while defining narrowing conversion through concrete assignments and expressions.
What you can do after
Evaluate C conversions for representability, information loss, precision loss, and mixed signedness.
How it connects
Connects narrowing conversion with implicit conversion, integer types, signedness, arithmetic, and floating-point types.

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. The section links point to the parts of the book it draws on.