Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading