twitter
    Find out what I'm doing, Follow Me :)

Scope Of Variables

Load the next program, scope.c and display it for a discussion of the scope of variables in a program.

int count; /* This is a global variable */


main( )
{
register int index; /* This variable is available only in main */
head1();
head2();
head3();
/* main "for" loop of this program */
for (index = 8;index > 0;index--) {
int stuff; /* This variable is only available in these braces */
for (stuff = 0;stuff <= 6;stuff++)
printf("%d",stuff);
printf(" index is now %d\n",index);
}
}
int counter; /* This is available from this point on */
head1()
{
int index; /* This variable is available only in head1 */
index = 23;
printf("The header1 value is %d\n",index);
}
head2()
{
int count; /* This variable is available only in head2 */
/* and it displaces the global of the same name */
count = 53;
printf("The header2 value is %d\n",count);
counter = 77;
}
head3()
{
printf("The header3 value is %d\n"counter);
}



The first variable defined is a global variable "count" which is available to any function in the program since it is defined before any of the functions. In addition, it is always available because it does not come and go as the program is executed. (That will make sense shortly.) Farther down in the program, another global variable named "counter" is defined which is also global but is not available to the main program since it is defined following the main program. Aglobal variable is any variable that is defined outside of any function. Note that both of these variables are sometimes referred to as external variables because they are external to any functions.

Return to the main program and you will see the variable "index" defined as an integer. Ignore the word "register" for the moment. This variable is only available within the main program because that is where it is defined. In addition, it is an "automatic" variable, which means that it only comes into existence when the function in which it is contained is invoked, and ceases to exist when the function is finished. This really means nothing here because the main program is always in operation, even when it gives control to another function. Another integer is defined