O'Reilly logo

21st Century C by Ben Klemens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 just how far they can take us.

  • We start 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 do similar tricks 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 viable option. By wrapping ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required