Local Variables

As we noted in Chapter 1, “Anatomy of a C Program,” and Chapter 2, “Functions,” the place where you declare a variable controls where the variable is visible. Declaring a variable within a function makes the variable local to that function; the variable can be seen only within the function.

The VISIBLE.C program below demonstrates local visibility. It contains a function named be_bop that tries to print the value of the local variable val.

/* VISIBLE.C: Demonstrate local visibility. */

#include <stdio.h>

void be_bop( void );

main()

{

int val = 10;

be_bop();

}

void be_bop( void )

{

printf( "val = %d", val ); /* Error! */

}

Notice where the val variable is declared. The declaration

int val = 10;

occurs within the main function, so val is local to main. When you compile VISIBLE.C, QuickC stops, providing this error message:

C2065: 'val' : undefined

What happened? The printf statement in the be_bop function

printf( "val = %d", val ); /* Error! */

can't “see” the variable val, which is declared locally within main. Outside the main function, in which val is declared, the variable doesn't exist.

You could eliminate the error message by declaring val externally, but most programmers would avoid that solution. If a variable has external visibility, any part of the program might change its value accidentally. A better solution is to pass the value of val to be_bop as a function argument, as shown in the program VISIBLE1.C below.

/* VISIBLE1.C: Demonstrate local visibility. */

#include <stdio.h>

void be_bop( int param );

main()

{

int val = 10;

be_bop( val );

}

void be_bop( int param )

{

printf( "%d\n", param );

}

The VISIBLE1.C program is identical to VISIBLE.C except for two changes. The be_bop function now can accept an argument, and the statement that calls be_bop passes the value of val as an argument. These changes allow the be_bop function to print the value of val without the drawback of making val external.

Most local variables are declared at the beginning of the function and are visible throughout the function. If you declare the variable later in the function, it is visible only to statements that follow the declaration.

The reason for this rule is simple: QuickC, like all language compilers, reads your program line by line, from beginning to end. Until the compiler sees the variable's declaration, it must treat the variable as undefined. This rule applies to all variables, including external variables, as we'll see in the next section.

Although the practice isn't common, you can restrict a local variable's visibility even further by declaring it in a statement block inside a function. For instance, you might declare a variable within the body of the loop or conditional statement. In fact, any pair of curly braces limits the visibility of a variable declared within that pair.