liveBook · Manning

Data conversion

As explained in Modern C, Third Edition

A cast is an explicit C conversion construct that requests conversion of an expression to a specified type.

A cast is an explicit C conversion construct: it requests that an expression be treated as a specified type. For pointers, this can discard type information and prevent the compiler from detecting an incompatible target type. section 12.5

Inspecting an object byte by 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]); Casting from an object pointer to a character-type pointer is described as mostly harmless and can expose the object's representation. The result still depends on the platform's representation, such as byte order. section 12.5 section 12.0

Treat casts as exceptional operations rather than routine repairs:

  • Prefer compatible pointer types and carefully chosen types so the compiler can retain useful type information. section 12.5
  • Do not use a cast to silence a diagnostic when the pointed-to object has a different size or interpretation; the access can cause serious damage. section 12.5
  • Remember that a syntactically valid cast can hide an error because an untyped pointer no longer identifies the object type to the compiler. section 12.5
 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]);

View the complete byte-inspection listing that demonstrates a cast from an unsigned object pointer to an unsigned-character pointer. section 12.5

How Modern C, Third Edition covers it

How deep it goes
Explains pointer-type information loss, compiler diagnostics, and incompatible-object risks, but stops short of broader cast forms.
Examples
Uses byte inspection, incompatible pointer assignments, and conversion between object pointers and character pointers.
What it assumes
Assumes familiarity with C pointers and object types while relating casts to the memory model and object representations.
What you can do after
Evaluate/understand when a C cast discards type information and why character-pointer inspection is a limited exception.
How it connects
Connects casts with pointers, void pointers, object representations, unions, effective types, and alignment.

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