30. How Can I Better Organize My Programs?

Using Functions

image

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 would get in the way while learning new concepts. That is 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 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.

Form Follows C Functions

As you might know, C programs aren’t like BASIC programs. C was designed to force you to think in a modular style through the use of functions. A BASIC program is often just one very long program that isn’t broken into separate routines. (Some of the newer versions of BASIC, such as QBasic, now offer almost the same functionality that C offers.) 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 very much, break it into several functions. Each function should do one primary task. For instance, if you were writing a C program to get a list of numbers from the keyboard, sort them, and then print them to the screen, you could write all of this in one big function—all in main()—as the following program outline shows:

image

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 there are several distinct tasks that need to be done. This program might not require many lines of code, but it’s much better to get in the habit of breaking every program into distinct tasks.

Don’t use main() to do everything. In fact, you should use main() to do very little except call each of the other functions. A better way to organize this program would be to write separate functions for each task that the program is to do.

Note

image

Of course, every function shouldn’t be a single line, but make sure that each function acts as a building block and performs only a single task.

Here is a better outline for the program just described:

image

Note

image

Even though this program outline is longer than the previous one, this one’s better organized, and therefore, easier to maintain. The only thing that 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 DOS. 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.

Clue

image

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 printNums() to print a title with your name and the date at the top of the page, you might have printNums() call another function named printTitle(). printTitle() would then return to printNums() when it finishes. Here is the outline of such a code:

image

Note

image

Look at all the functions in the Blackjack game in Appendix B. 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 radios, contain lots 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 if and only if you define the variable (such as int i;) before a function name.

• A variable is local if and only if you define it after an opening brace. A function always begins with opening braces. Some statements, such as while, also have opening braces, and you can define local variables within those braces as well.

Clue

image

An opening and closing brace enclose what is known as a block.

Given these rules, it should be obvious that l1 and l2 are local variables and that g1 and g2 are global variables in the following program:

image

Clue

image

The variable g2 is global because it’s defined before a function (prAgain()).

Local variables are usable only within their own block of code. Therefore, l1 could never be printed or changed in prAgain() because l1 is local to main(). Conversely, l2 could never be used in main() because l2 is visible only to prAgain(). The variable g1 is visible to the entire program. g2 is visible only from its point of definition down.

Clue

image

All global variables are known from their points of definition down in the source file. Don’t define a global variable in the middle of a program (as is done in the preceding program) because its definition can be too hard to find during debugging sessions. You should limit (or eliminate) the use of globals. If you use them at all, define all of them before main() where they are easy to find (such as if you need to change them or look at their defined data types).

Warning

image

There is a problem with the program outline shown earlier. If you use only local variables (and you should always try to), the variable values input in getNums() can be neither sorted in sortNums() nor printed in printNums()! Stay tuned, because the next chapter shows you the solution.

Rewards

image

• Define local variables after a block’s opening brace. Define global variables before a function begins.

• Local variables are safer than global variables, so use local variables as much as possible.

• Break your programs into lots of functions to ease maintenance and speed development time.

Pitfalls

image

• Don’t define global variables in the middle of a program. They’re too hard to locate if you do.

• Don’t start out using global variables. As your program grows, you may occasionally see the need for a global variable and add one then. (The next chapter explains more about using local variables in place of globals.)

In Review

The goal of this chapter was to teach you the building-block approach to writing C programs. Long programs can become unwieldy unless you break them into several separate functions. One long main() function is analogous to a long book without chapter divisions. Break your long programs into separate functions and have each function perform a single, separate task in the program.

Once you divide your programs into several functions, you have to consider how variables are used throughout the code. Local variables are defined inside a function and are usable only in that function. The opposite of a local variable is a global variable, whose value is usable in all functions after its definition. Global variables are frowned upon. Local variables are safer because you can limit their access to only those functions that need to use them. In the next chapter, you’ll learn how to share local variables between functions.

Code Example

image

Code Analysis

This program contains three variables, two of which are global (name and weight) and one that is local to main() (age). The first function, main(), is put on hold when it calls nextFun(). When nextFun() concludes, the last line in main() is free to finish.

The nextFun() function can’t use the value of age because age is local to main() and therefore usable only in main().

This program contains a comment full of asterisks before the nextFun() function. Programmers often use such separating comments to distinguish one function from another. When looking through the code, you can more easily find the function you’re looking for.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset