Chapter 7. Advanced Functions: Turn your functions up to 11

image with no caption

Basic functions are great, but sometimes you need more.

So far, you’ve focused on the basics, but what if you need even more power and flexibility to achieve what you want? In this chapter, you’ll see how to up your code’s IQ by passing functions as parameters. You’ll find out how to get things sorted with comparator functions. And finally, you’ll discover how to make your code super stretchy with variadic functions.

Looking for Mr. Right...

You’ve used a lot of C functions in the book so far, but the truth is that there are still some ways to make your C functions a lot more powerful. If you know how to use them correctly, C functions can make your code do more things but without writing a lot more code.

To see how this works, let’s look at an example. Imagine you have an array of strings that you want to filter down, displaying some strings and not displaying others:

int NUM_ADS = 7;
char *ADS[] = {
  "William: SBM GSOH likes sports, TV, dining",
  "Matt: SWM NS likes art, movies, theater",
  "Luis: SLM ND likes books, theater, art",
  "Mike: DWM DS likes trucks, sports and bieber",
  "Peter: SAM likes chess, working out and art",
  "Josh: SJM likes sports, movies and theater",
  "Jed: DBM likes theater, books and dining"
};

Let’s write some code that uses string functions to filter this array down.

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.