Home » C programming language

How to access global variables using 'extern' in C?



We know that, global variables are accessible in all other functions in c programming language, but we cannot access them normally in a function if function have the variables with the same names as the global variables.

Let's consider the following example

This example has one global variable x and one local variable x, both variables have the same name, now I will try to print the value of x in this example.

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

Output

x= 100

See the output, here the value of x is 100 which is the value of local variable x, so here we are unable to access global variable x.

Access global variable using 'extern'

By declaring a variable as extern we are able to access the value of global variables in c language. Basically, extern is a keyword in C language that tells to the compiler that definition of a particular variable is exists elsewhere.

Consider the following example

Here I am declaring x as extern and then the print the value of x.

#include <stdio.h>
int x=50;
int main()
{
	int x=100;
	{
	    extern int x;
	    printf("x= %d\n",x);
	}
	printf("x= %d\n",x);
	return 0;
}

Output

x= 50
x= 100

See the output, x= 50 is the value of the global variable x and x= 100 is the value of local variable x.






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.