Search code examples
c++cfunctionmemoryglobal-variables

Does the use of a global variable within a function cause a local copy to be created


Unfortunately I can't find anything on the subject although I can't believe this question hasn't been asked before.

When I use a global variable inside a function, is a local copy of the variable created as with a passed argument or is the global variable accessed directly? Does it even make sense to define a global variable as a parameter of a function using the reference declarator & or as a pointer *?

PS: I know that global variables are a bad practice, but I'm programming for a microcontroller where it sometimes make sense to use global variables.


Solution

  • Globals are not copied when used in a function. There are used directly. For example:

    #include <stdio.h>
    
    int x;
    
    void foo1()
    {
        x=2;
    }
    
    void foo2()
    {
        printf("%d\n", x);
    }
    
    int main()
    {
        foo1();
        foo2();
        return 0;
    }
    

    Output:

    2
    

    The first function modifies x, and the second reads the modified x and prints it.

    If globals were in fact copied in each function, it would be impossible to modify them, and the above code would instead print 0.