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

(Romina) #1
Note

Even though this program outline is longer than the previous one, this one is better
organized and, therefore, easier to maintain. The only thing main() does is control
the other functions by showing an overview of how they’re called.

Each separate function does its thing and then returns to main(), where main() calls the next
function until there are no more functions. main() then returns to your operating system. main()
acts almost like a table of contents for the program. With adequate comments, main() lets you know
exactly what functions contain code you need to change.


Tip

A good rule of thumb is that a function should not take more lines than will fit on a
single screen. If the function is longer than that, you’re probably making it do too much.
In high school, didn’t you hate to read literature books with l-o-n-g chapters? You’ll
also dislike working on programs with long functions.

Any function can call any other function. For example, if you wanted buildContact() to print the
complete contact info after it was entered, you might have buildContact() call another function
named printContact(). printContact() would then return to buildContact() when it
finishes. Here is the outline of such a code:


Click here to view code image


main()
{
assignID(); // Sets up a unique ID for the new employee
buildContact(); // Enters the employee's basic contact info
payrollAdd(); // Adds the new employee to the payroll system
return 0;
}
/* Second function, one that sets an ID for the new employee
assignID()*/
{
// Block of C code to set up a unique ID for the
// new employee
return;
}
/* Next function—the contact building function */
buildContact()
{
// Block of code to input the employee's
// home address, phone number, birth date,
// and so on
printContact();
Free download pdf