Chapter 5. Functions

With the various assignment statements and flow of control options we’ve seen so far, you are now primed to solve just about any problem meant for computers. But solving a problem turns out to be only about half of the, uh, problem. Whether you are coding for work or for fun, you invariably need to go back to code you have already written. You might be fixing a small bug or adding a missing feature. You may be using a previous project as a starting point for a new one. In all of these moments, the maintainability of your code becomes almost as important as the initial effort to get the code working. Breaking up a problem to make it manageable while you are solving it can have a beneficial effect on the code you end up writing—which also has a beneficial effect on its readability and maintainability.

Core to this idea of tackling smaller problems on the way to tackling the whole one is the use of functions or procedures. Functions help you encapsulate logic—the statements and control structures you are learning to code. In C, you can write and call as many functions as you need.1 C doesn’t really distinguish between the word “function” and the word “procedure,” although some languages do. (In those languages, the difference is often whether or not a piece of code returns a value or simply executes a set of statements.) I’ll mostly use the term function, but if you see discussions of a procedure (or routine, same idea) here or in any of your ...

Get Smaller 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.