Learn C
#include "structstypes/opaque_types.h"

Opaque Types & Forward Declarations in C

#concept

An opaque type hides its layout: the header declares typedef struct Handle Handle; with no body, so users hold only pointers and can never see inside, sizeof it, or depend on its fields. All manipulation flows through your functions (Handle *create(void); void destroy(Handle *);) β€” true encapsulation in a language without private.

FILE* is the canonical opaque type. The pattern also breaks circular header dependencies (forward-declare instead of including) and shrinks rebuilds. Cost: heap allocation per object (no stack instances of incomplete types) and a function call per access β€” the standard price of hidden implementation.

#how it works
1

Declare without defining

typedef struct Config Config; in the header β€” a complete type name with deliberately missing layout.

2

Pointers only outside

Users declare Config *c; and pass it around β€” sizeof, member access, and stack instances all correctly rejected.

3

Define once, privately

The .c file holds the full struct definition plus create/destroy/access functions β€” the single place layout exists.

4

Break header cycles

Mutually referencing structs forward-declare each other instead of including in circles β€” compile-time deadlock resolved.

#example
// counter.h: typedef struct Counter Counter;
// Counter *counter_new(void);
// void counter_bump(Counter *c);
// int counter_get(const Counter *c);
// counter.c defines struct Counter { int n; }; plus bodies.
// main.c: Counter *c = counter_new(); counter_bump(c);
Output
(counter reads 1; layout invisible to main.c)
1main.c sees only the name Counter β€” its size, fields, and layout are unknowable there.
2Creation, mutation, and reading all flow through functions owning the private definition.
3The counter works fully while remaining a black box β€” encapsulation without language support.
#use cases
Library APIs hiding implementation structs from users (FILE* pattern)
Breaking circular dependencies between mutually-referencing headers
ABI stability: changing private fields without recompiling callers
Enforcing access through validated functions instead of raw fields

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself β€” building beats watching.