C Tutorial (30) : Function and local-global variables

Typical computer programs are not the 20- to 30-line variety that you see in tutorials/textbooks. In the “real world,” computer programs are much longer. 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. 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.

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:

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

Note : Breaking programs into smaller functions is called structured programming.

A better way to organize this program would be to write separate functions for each task the program is to do. Of course, not every function should be a single line, but make sure each function acts as a building block and performs only a single task.

Here is a better outline for the program just described:

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
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;
}

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.

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.

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:

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();
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()
}

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 and Global Variables

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.

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 int i;) before a function name.
  • A variable is local 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.

Note : 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:

/* The program is a simple demonstration of the difference between 
   global variables and local variables. */

#include  <stdio.h>

int g1 = 10;

main()
{
float l1; l1 = 9.0;

printf("%d %.2f\n", g1, l1); // prints the 1st global and first 
                             // local variable

prAgain(); // calls our first function 
return 0;
}

float g2 = 19.0;
prAgain()
{
int l2 = 5;

// Can't print l1--it is local to main 
printf("%d %.2f %d\n", l2, g2, g1); 
return;
}

Note : You might not yet completely understand the return 0; statement. To make matters worse, return by itself is used at the end of the prAgain() function. You’ll find a detailed description for return in the next tutorials.

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.

Note : 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.

Disk files – Random access < Prev             Next > Passing arguments/variables

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s