Imagine that a function is a building with a person (Fred) standing in
the doorway. This person can see certain things: other people and other
buildings, out in the open. But Fred cannot see certain other things,
such as the people inside the other buildings. Just so, some variables
in a C program, like the people standing outside, are visible to
nearly every other part of the program (these are called global
variables), while other variables, like the people indoors, are hidden
behind the "brick walls" of curly brackets (these are called
local variables).
Where a variable is visible to other C code is called the scope of
that variable. There are two main kinds of scope, global and local,
which stem from the two kinds of places in which you can declare a
variable:
Global scope is outside all of the functions, that is, in the
space between function definitions -- after the #include lines,
for example. Variables declared in global scope are called global
variables. Global variables can be used in any function, as well as in
any block within that function.
#include <stdio.h>
int global_integer;
float global_floating_point;
int main ()
{
exit (0);
}
You can also declare variables immediately following the opening bracket
({) of any block of code. This area is called local
scope, and variables declared here are called local variables.
A local variable is visible within its own block and the ones that block
contains, but invisible outside its own block.
#include <stdio.h>
int main()
{
int foo;
float bar, bas, quux;
exit (0);
}