top of page

Scope in C: Where Can My Variable Be Used?

Introduction


In real life, we use the word "scope" to map out a specific boundary or region. Similarly, in programming, "scope" refers to the range in which a variable or function can be used.



As you can imagine, global variables can be accessed anywhere in the program, while on the flipside, local variables only exist within the functions they were defined.


#include <stdio.h>

int double(int y);

int x = 12;

int main(void)
{
	double(x);
	printf("%i\n", x);
}

int double(int y)
{
	return y * 2;
}

In this case, x would be the global variable, as it's declared outside of any function and on the main file itself. Of course, y would be our local variable, as it's declared within the function double().


What do you think this this program print?


Oddly enough, "12" would be printed to the terminal, even though we seemingly doubled the value of x. But why...?


Local Variables in Functions


It turns out, when variables are passed into a function as parameters, a copy of the passed variable is made.


Thus, the original variables passed remain unchanged, while the copy of that variable is in fact modified.


In the example above, the function double was called on the variable x. Now, within that function, a copy of x is made, storing the value of x (12) in the variable y. Finally, twice of y is returned.


Take a moment to think of a way to directly modify the value of x. One such option is to assign x to double its original value:


...

int main(void)
{
	x = double(x);
	printf("%i\n", x);
}

...

Another way to achieve this is to modify the double function so that it takes no parameters and returns twice the value of the global variable x (which can be accessed in functions):


...

int double(void)
{
	return x * 2;
}

...

Same Name, Different Scopes


Things tend to get tricky when multiple variables share the same name. What will this program return?


#include <stdio.h>

int x = 2;

int main(void)
{
	int y = double(x);
	printf("%i, %i\n", y, x);
}

int double(int x)
{
	x *= 2;
	return x;
}

In this case, '4, 2', is printed because the local variable within double() (x) takes priority over the global variable x within its scope. Thus, the copy of the global variable x was modified in double(), not the global variable itself, meaning x is unchanged.


How about this program?


#include <stdio.h>

int main(void)
{
	int x = 12;
	int y = double(x);
	printf("%i, %i\n", y, x);
}

int double(int x)
{
	x *= 2;
	return x;
}

This will print '24, 12' because the x in main() has a separate scope from the x in double().


Final Thoughts


Hopefully by the end of the blog you're better prepared for the next time you get a scope error of some sort (perhaps disguised as a 'redeclaration' or an 'undeclared variable name').


Thanks for reading!

Comments


bottom of page