Chapter 5. Structs, Unions, and Bitfields: Roll your own structures

Most things in life are more complex than a simple number.
So far, you’ve looked at the basic data types of the C language, but
what if you want to go beyond numbers and pieces of text, and model things in the real world? structs allow
you to model real-world complexities by
writing your own structures. In this chapter, you’ll learn how to
combine the basic data types into
structs, and even handle life’s uncertainties with unions. And
if you’re after a simple yes or no, bitfields may be just what you need.
Sometimes you need to hand around a lot of data
You’ve seen that C can handle a lot of different types of data: small numbers and large numbers, floating-point numbers, characters, and text. But quite often, when you are recording data about something in the real world, you’ll find that you need to use more than one piece of data. Take a look at this example. Here you have two functions that both need the same set of data, because they are both dealing with the same real-world thing:


Now that’s not really so bad, is it? But even though you’re just passing four pieces of data, the code’s starting to look a little messy: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access