C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

30. Organizing Your Programs with Functions


In This Chapter


  • Adding functions to programs

  • Choosing between global and local variables


Typical computer programs are not the 20- to 30-line variety that you see in textbooks. In the “real
world,” computer programs are much longer—but long programs contain lots of code that can get in
the way while learning new concepts. That’s why, until this point, you’ve seen fairly short programs
that contain all their code in main().


If you were to put an entire long program in main(), you would spend a lot of time trying to find
anything specific if you later needed to change it. This chapter is the first of three chapters that
explore ways to partition your programs into sections via multiple functions. Categorizing your code
by breaking it into sections makes programs easier to write and also easier to maintain.


People have to write, change, and fix code. The clearer you make the code by writing lots of functions
that do individual tasks, the faster you can get home from your programming job and relax! As you’ll
see, separate functions let you focus on code that needs changing.


Form Follows C Functions


C was designed to force you to think in a modular style through the use of functions. A C program
isn’t just one long program. It’s made up of many routines named, as you know, functions. One of the
program’s functions (the one always required and usually listed first) is named main().


If your program does a lot, break it into several functions. Each function should do one primary task.
For instance, if you were writing a C program to assign an ID number to a new employee, get the
person’s contact information, and then add him or her to the payroll, you could write all of this in one
big function—all in main()—as the following program outline shows:


Click here to view code image


main()
{
// Not a working program, just an outline...
...
// First section of code that assigns an ID number to an
// employee
...
// Next section of code has the user input basic contact info
...
// Final section of code adds the employee to the payroll
// system
...
return(0);
}

This program does not offer a good format for the tasks you want accomplished because it’s too
sequential. All the code appears in main(), even though several distinct tasks need to be done. This

Free download pdf