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.

C Language Tutorial »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.