C Reference ยท Concepts and Tools
Common C idioms and patterns
Recurring patterns in real C code: array size macros, goto cleanup, sizeof *p allocation, opaque handles, bit flags, X-macros, tagged unions and do-while macros.
An idiom is a short pattern that C programmers recognize on sight. Because the language is small, much of its practice lives in idioms: how to size an array, how to release resources on every error path, how to write a macro that behaves like a statement. Learning them makes other people's C readable and your own code more reliable.
This page collects the ones you will see most often. Each is small, but each exists because the obvious alternative has a trap.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
The idioms
| Idiom | Why |
|---|---|
sizeof(a) / sizeof((a)[0]) |
Element count of a real array. Wrong for a pointer or an array parameter, which has decayed (see Array parameters). |
p = malloc(n * sizeof *p) |
The size follows the pointer's type, so changing the type needs no second edit. Check for overflow in n * size for untrusted n, or use calloc. |
goto cleanup on errors |
One place frees resources in reverse order; avoids duplicated cleanup and leaks. See goto. |
free(p); p = NULL; |
Turns a later double free into a harmless no-op and a use-after-free into a crash. |
do { ... } while (0) |
Lets a multi-statement macro be used before else. |
| Parenthesized macro arguments | #define SQ(x) ((x) * (x)); still evaluates x twice. |
Bit flags with 1u << n |
Set ` |
| Designated initializers | Tables and configs stay valid when fields are reordered or added. See Designated initializers. |
| Opaque pointers | Header declares typedef struct Foo Foo;, the .c file defines it: users cannot touch the fields. See Opaque types. |
| Tagged union | A kind field plus a union models "one of several shapes". |
Callbacks with void *user |
Gives a plain function pointer access to state. See Callbacks. |
| X-macros | One list generates enum, names and tables so they cannot drift apart. See X-macros. |
for (;;) or while (1) |
The conventional infinite loop. |
(void)expr; or [[maybe_unused]] |
States that ignoring a value or parameter is deliberate. |
snprintf(buf, sizeof buf, ...) |
Bounded formatting; check that the result is smaller than the size to detect truncation. |
Usage notes
- An idiom is a convention, not a guarantee.
sizeof *pis safe only whenpis a valid pointer type, notvoid *. gotocleanup is accepted style in the Linux kernel, many libraries and CERT guidance, but only jump forward within one function, never past variable-length array declarations.- A
do/while(0)macro cannot return a value; use astatic inlinefunction or a statement expression (GCC extension, not portable) if you need one. - X-macros hurt debugging because the compiler reports errors in the expanded code; keep the lists short.
- Prefer functions to macros whenever types and evaluation allow it.
Related
- C coding style, Data structures in C, Macro pitfalls
- malloc, calloc, free
- Tutorial: Best practices, Macros