: At many places I have seen that programmers pass global variables
:to functions in c. I am not able to figure out why they do so. need
:some clues on this. somewhere i heard that this philosophy is from
bject orieted world but is it applicable for c?
Abstraction and Encapsulation.
Suppose I create a global variable in a routine and I use it
-as- a global variable in lower-level routines.
Suppose now that I change my mind about the implementation detail of
whether it should be a global variable or a file-scoped variable or
some malloc()'d storage or an automatic variable. Suddenly I need
to hunt down and change -all- the global references to
the variable.
If, on the other hand, I create a global variable, and as far
as is practical, I pass it explicitly to routines, then when I change
my mind about the storage paradigm, I do not have to change those
lower-level routines.
Even in cases where it is not really practical to pass the variable
through many levels, it is not uncommon to write accessor functions
that get or set the value of the variable, rather than just going
ahead and reading or writing directly to the global.
Creating accessor functions tends to divorce the implementation details
from semantic details. The accessor functions might make sanity
checks, or might hide details such as whether a value is stored
as an inddpendant variable or as a bitfield. An accessor function
might invoke associated behaviour (e.g., flushing a buffer), or
might synthesize the variable by way of others. If you imagine a
data structure representing triangles, then an accessor function
that allowed setting the coordinates of one of the vertices might
take on the ancillary job of recalculating angles -- or in an accessor
function for a data structure representing a square, setting the
coordinates of one of the vertices might result in the recalculation
of the location of two of the other vertices.
One -could-, in each of the above cases, have directly bashed the
appropriate global variables (and then called any necessary
follow-on routines), but if you think about the situation, you will
realize that just because a variable -happens- to be implemented as
a global doesn't mean that the variable is functionally independant
of all other variables. Sbstracting away the representation issues
can sometimes result in much better code that is more maintainable
and more extensible.