cfunctionvariables

Is it possible to access a parameter of a function from another function in C?


Is it possible to access the value of a variable from a function within another function. You can assume that the first function is called in the main one. Here is an example:

int foo (int x) {
    int z;
    // Do things...
    return 0;
}

int bar () {
    // Access value of z here.
    // Do more things...
    return 0;
}

Solution

  • Outside of foo its (non-static) local variables don't exist. That's the whole point of it being a local variable.

    If you need to communicate state between functions you have two basic methods:

    Global variables

    int z = 4;
    
    void foo(int x) {
        z = z + x;
    }
    
    void bar(void) {
        z = z * 2;
    }
    
    int main(void) {
        foo(6);
        bar();
    
        printf("%d\n", z);
        // prints 20
    }
    

    Avoid this whenever possible. It makes debugging substantially harder because functions cannot be tested without considering what every other function might be doing to the state of that global variable.

    Via function arguments and return values

    Much better is to pass information via a function's arguments and return values. For small data types and simple manipulations, it's probably best practice to pass variables by value and return an updated value from the function.

    For larger data types where copying would be inefficient, or where multiple arguments need to be updated, you can pass a pointer to another value and use that to update the value it points to.

    An example of passing a pointer:

    void foo(int *z, int x) {
        *z = *z + x;
    }
    
    void bar(int *z) {
        *z = *z * 2;
    }
    
    int main(void) {
        int z = 4;
        foo(&z, 6);
        bar(&z);
    
        printf("%d\n", z);
        // prints 20
    }