liveBook · Manning

Opaque type

As explained in Modern C, Third Edition

An opaque data type is a type whose representation and implementation details are hidden from code that uses it.

An opaque type hides its representation from client code. Users rely on functional interfaces rather than accessing fields, layout, or other implementation details. In C, FILE* illustrates the pattern: FILE identifies a stream, but its contents remain unknown; client code passes the pointer to functions such as fputc and fputs and can test whether it is null. section 8.4.1

int putchar(int c);
int puts(char const s[static 1]);

The output interface exposes operations without exposing the representation of the stream object. section 8.4.1

Use opaque types according to these rules:

  • Call the documented functions instead of depending on the hidden representation. section 8.4.1
  • Do not infer field layout, base types, or other implementation details from the public typedef. section 8.4.1 section 19.5

jmp_buf hides an array type

The typedef jmp_buf is opaque: its base type and individual fields are unspecified. An object of type jmp_buf cannot be assigned, and passing it as a function parameter is rewritten to a pointer to its hidden base type. This supports setjmp and longjmp, but the declaration trick has awkward semantics and is explicitly unsuitable as a model for new types. section 19.5

[[noreturn]] void longjmp(jmp_buf target, int condition);
int setjmp(jmp_buf target);    // Usually a macro, not a function

setjmp and longjmp show the public operations that manipulate an opaque jmp_buf without exposing its representation. section 19.5

How Modern C, Third Edition covers it

How deep it goes
Explains interface discipline and C typedef mechanics, but stops short of specifying either hidden representation.
Examples
Uses FILE* with fputc and fputs, and jmp_buf with setjmp and longjmp.
What it assumes
Assumes familiarity with pointers, typedefs, function parameters, and null testing.
What you can do after
Evaluate/understand C interfaces without relying on opaque representation details or copying unsuitable typedef techniques.
How it connects
Connects opaque types with functional interfaces, FILE streams, typedefs, arrays, setjmp, and longjmp.

Also explained in

Compare how 4 books explain opaque type →

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.