In C, every function can have its own variable declarations. In previous
lessons you learned how to declare variables within the main function. You can
use the same kinds of statements to declare variables inside other functions.
Take a look at the distance function in ``rods.c''. The line
float delta_x, delta_y;
declares two variables inside the distance function.
These variables are ``local'' variables! When you declare a variable
inside one function of a program, that variable is accessible or ``visible''
only within that function. A variable that is declared in one function is
not accessible to any other functions in the program.
This means, for example, that in the main program unit of ``rods.c'', you
can't write statements that refer to the variables delta_x and
delta_y that are declared inside the distance function. Similarly,
statements within the distance function can't refer to the variables that
are declared in the main program.
Computer scientists have a word for this idea: scope. The scope of a
variable is the part of the program text in which the variable is accessible.
In all the code we've seen, the scope of each variable is the function in which
that variable is declared.
So if the functions within a program can't access each other's variables, then
how does information get from one function to another?
Click here for the answer.
(In truth, these aren't the only ways in which you can send information from
one part of a program to another. For example, in C it is possible to define
``global'' variables that can be accessed from every part of a program. But
for now you should restrict yourself to using function arguments and return
values to carry information between program parts.)
Eric N. Eide
Hamlet Project
Department of Computer Science
University of Utah