How To Access Global Variable Using Extern Keyword In C

Prashant | Fri, 12 Jun, 2020 | 138

How to access Global variable using extern keyword

As we all knowthat global variables are accessible from all the places, but what if local variables are of same name. At that time local variables are given priority over global variable.

So how do we use global variable at that time, so we can use extern keyword in order to access global variables. We will see this using examples here.

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.

 

 

 

 

 

 

Related Articles :- 

1Introduction And Getting Started With C

2Basic Of C Language

3. Why We Should Use C Language

4. Applications Of C Programming

5. Basic Rules For Writting C Program

6. Keywords In C Language

7. Comments In C Programming

8. Tokens In C

9. Difference Between Int Main And Void Main

10. C Processor And Macros

11. Variables In C

12. Types Of Variables In C

13. Difference Between Local And Global Variable

14. Difference Bwtween Auto / Extern / Static Variable

15. Constant In C

16. How To Access Global Variable Using Extern Keyword In C

17. Exit And Return Staterment In C

18. Print Float Value Upto N Decimals In C Programming

19. How To Print Multiline Message Using Single Printf In C Programming ?

20. What Value Returned By Scanf Function In C Language ?

21. What Value Is Returned By Printf And Scanf In C

22. What Do 'Lvalue' And 'Rvalue' Mean In C/C++?

23. Errors In C Programming ?

0 comments
Leave a comment