O'Reilly logo

Head First C by Dawn Griffiths, David Griffiths

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 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 to look a little messy: ...

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