Chapter 10. Better Structures
Twenty-nine different attributes and only seven that you like.
The Strokes, “You Only Live Once”
This chapter is about functions that take structured inputs, and improving the user interface to our libraries.
It starts by covering three bits of syntax introduced to C in the ISO C99 standard: compound literals, variable-length macros, and designated initializers. The chapter is to a great extent an exploration of all the things that combinations of these elements can do for us.
With just compound literals, we can more easily send lists to a function. Then, a variable-length macro lets us hide the compound literal syntax from the user, leaving us with a function that can take a list of arbitrary length: f(1, 2)
or f(1, 2, 3, 4)
would be equally valid.
We could use similar forms to implement the foreach
keyword as seen in many other languages, or vectorize a one-input function so that it operates on several inputs.
Designated initializers make working with structs much easier, to the point that I’ve almost entirely stopped using the old method. Instead of illegible and error-prone junk like person_struct p = {"Joe", 22, 75, 20}
, we can write self-documenting declarations such as person_struct p = {.name="Joe", .age=22,
.weight_kg=75,
.education_years=20}
.
Now that initializing a struct doesn’t hurt, returning a struct from a function is also painless and can go far to clarify our function interfaces.
Sending structs to functions also becomes a more ...
Get 21st Century C, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.