Search code examples
cglobal-variables

Global variable as an argument of function call in C


While passing global variable in function parameter, is it passed as reference or value?

For example:

#include <stdio.h>

int global_var = 5;

int foo(int p) { // p for parameter
    return p * 10;
}

int main() {
    return foo(global_var);
}

Solution

  • It is passed by value. The following code shows that this is the case:

    #include <stdio.h>
    
    int global = 5;
    
    void foo(int bar){
        bar = 6;
        printf("bar = %d\nglobal = %d", bar, global);
    }
    
    int main(){
        foo(global);
        return 0;
    }
    

    The output is:

    bar = 6

    global = 5

    In this code global was passed as a parameter for foo, we called this parameter bar. So at the beginning global and bar are two different variables both having the value 5. But then bar is assigned the value 6 and since the argument was referenced by value, global stays at 5.

    To pass the variable by reference, use pointers:

    #include <stdio.h>
    
    int global = 5;
    
    void foo(int *bar){
        *bar = 6;
        printf("bar = %d\nglobal = %d", *bar, global);
    }
    
    int main(){
        foo(&global);
        return 0;
    }
    

    Now the output is:

    bar = 6

    global = 6