liveBook · Manning

Data conversion

As explained in Modern C

Type conversion is the transformation of a C value from one type to another compatible type.

Type conversion transforms a C value from one compatible type to another. It may happen implicitly when an expression or function call requires a different type. For example, with `extern double fbar(double);`, the call `fbar(2)` converts the signed integer `2` to the double value `2.0`; the known return type then makes division by `2` floating-point division. TAKEAWAY: A prototype gives the compiler enough type information to perform and check these conversions. section 7.1

Pointer conversions require sharper distinctions:

  • Adding a qualifier, such as converting `float*` to `float const*`, is permitted. section 12.5
  • Converting an object pointer to `void*` and back can preserve the pointer type when the destination matches. section 12.5

Inspecting an object representation

An explicit cast has the form `(T)X`. The following code deliberately converts a pointer to `unsigned` into a pointer to character type, then prints each byte: `unsigned val = 0xAABBCCDD;` `unsigned char* valp = (unsigned char*)&val;` `for (size_t i = 0; i < sizeof val; ++i)` ` printf("byte[%zu]: 0x%.02hhX\n", i, valp[i]);` This is a special-purpose inspection of the object representation. In general, casts erase type information and commonly conceal design errors; use them only for exceptional cases such as byte-level inspection. section 12.5

Prefer compatible types and let prototypes expose mismatches. A cast tells the compiler to accept an assertion about the object behind a pointer, but it does not make that assertion true. TAKEAWAY: Do not use casts unless a narrowly defined operation, such as examining bytes, requires one. section 12.5 section 7.1

How Modern C covers it

How deep it goes
Explains implicit and explicit conversions through code examples, but defers broader pointer and object-representation rules.
Examples
Uses a double-valued function call, pointer-conversion cases, and byte printing through an unsigned-character pointer.
What you can do after
Diagnose conversion mismatches, interpret implicit function conversions, and restrict explicit casts to justified byte-level inspection.
How it connects
Connects conversion to function prototypes, pointers, void pointers, qualifiers, object representations, and undefined behavior.

Also explained in

Compare how 21 books explain data 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.