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.





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.