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

(Romina) #1
return;
}
/* Fourth function to add employee to the payroll */
payrollAdd()
{
// Code to set the new employee's salary,
// benefits, and other info in the
// payroll system
return;
}
/* Fifth function to print an entire contact onscreen */
printContact()
{
// Code to print the contact
return; // Returns to buildContact(), not to main()
}

Note

Look at all the functions in the Draw Poker game in Appendix B, “The Draw Poker
Program.” The program is only a few pages long, but it contains several functions.
Look through the code and see if you can find a function that calls another function
located elsewhere in the program.

The entire electronics industry has learned something from the programming world. Most electronic
components today, such as televisions, computers, and phones, contain a lot of boards that can be
removed, updated, and replaced without affecting the rest of the system. In a similar way, you’ll be
able to change certain workings of your programs: If you write well-structured programs by using
functions, you can then change only the functions that need changing without having to mess with a lot
of unrelated code.


Local or Global?


The program outline explained in the preceding section needs more code to work. Before being able
to add code, you need to take a closer look at variable definitions. In C, all variables can be either
local or global. All the variables you have seen so far have been local. Most of the time, a local
variable is safer than a global variable because a local variable offers itself on a need-to-know
access. That is, if a function needs a variable, it can have access to another function’s local variables
through a variable-passing process described in the next chapter.


If a function doesn’t need to access another function’s local variable, it can’t have access. Any
function can read, change, and zero out global variables, so they don’t offer as much safety.


The following rules describe the difference between local and global variables:



  • A variable is global only if you define the variable (such as inti;) before a function name.

  • A variable is local only if you define it after an opening brace. A function always begins with

Free download pdf