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

image with no caption

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:

image with no caption
image with no caption

Now that’s not really so bad, is it? But even though you’re just passing four pieces of data, the code’s starting ...

Get Head First C 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.