Re: Paasing global variables to functions



In article <1122532047.716912.229400@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
<ankisharma@xxxxxxxxx> wrote:
>
>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
>object orieted world but is it applicable for c?

I don't know about "many places", but a scenario like this is
plausible:

--- version 1 ---------------------------------
int x; /* global variable */

void foo(int n)
{
/* do something with n */
}

int main(void)
{
x = 4;
foo(x);
...
}

--- version 2 ---------------------------------
int x; /* global variable */

void foo(void)
{
/* do something with x */
}

int main(void)
{
x = 4;
foo();
...
}

If the function foo() does not change the value of the
global variable, then the two versions are equivalent, but
prefer version 1 because the function foo() is self-contained
therefore easier to maintain. And if some day you redo your
program so that the global variable goes away, the function
foo() won't be affected.

--
Rouben Rostamian
.



Relevant Pages

  • Re: pass by reference is valid?
    ... I was talking to some C programmers and they told me there is no such ... thing as pass by reference in C since you are just passing an address ... C just cares that you pass the correct type of arguments (int, float, ... c global variables or local. ...
    (comp.lang.c)
  • Re: Moving from 8051 to AVR
    ... Getting rid of global variables is not "good programming practice". ... int foo; ...
    (comp.arch.embedded)
  • Re: printing the permutation, help
    ... People might not be able to see the post you are replying to. ... Don't use global variables without a very good reason. ... Implicit int was removed in the C99 standard and many considered it bad style even before then, and you don't return a value anyway! ... there are plenty of solutions without bothering with recursion. ...
    (comp.lang.c)
  • Re: Resources about program design in C
    ... an interest in the reasoning behind global variables in C programs. ... A function should isolate its implementation details from the ... imagine a module that implements a stack ... static int stack_ptr; ...
    (comp.lang.c)
  • location of stack and heap varies -- why?
    ... int main{ ... were the same from execution to execution. ... I don't think the Linux systems can be using a single-address-space ... different addresses for the global variables, ...
    (comp.unix.programmer)