www.easyCPlusPlus.com

Easy C++

www.easyCPlusPlus.com

C Tutorial - Lesson 15: Scope and Program Structure

Local Variables

by John Kopp

Support this site at no cost to you

Welcome to easyCPlusPlus.com's tutorial on C programming. This is the final lesson. It covers several topics that are relevant to creating real C programs to solve real problems: variable scope, static variables and program structure.

Local Variables
The scope of a variable is simply the part of the program where it may be accessed or written. It is the part of the program where the variable's name may be used. If a variable is declared within a function, it is local to that function. Variables of the same name may be declared and used within other functions without any conflicts. For instance,

int fun1()
{
    int a;
    int b;
    ....
}

int fun2()
{
    int a;
    int c;
    ....
}

Here, the local variable "a" in fun1 is distinct from the local variable "a" in fun2. Changes made to "a" in one function have no effect on the "a" in the other function. Also, note that "b" exists and can be used only in fun1. "C" exists and can be used only in fun2. The scope of b is fun1. The scope of c is fun2. Note that main is also a function. Variables declared after the opening bracket of main will have all of main as their scope.

int fun1();
int fun2();

int main()
{
    int a;
    int b;
    int x,y,z;

    x = fun1();
    y = fun2();

    return 0;
}

int fun1()
{
    int a;
    int b;
    ....
}

int fun2()
{
    int a;
    int c;
}

So here, a, b, x, y and z are local to main, a and b are local to fun1 and a and c are local to fun2. Notice that in this example there are three distinct local variables all named "a". Local variables are also referred to as automatic variables. They come to life at the beginning of a function and die at the end automatically.

Previous Page       Next Page