Skip to main content

difference between global variable and extern variable

Global variable and extern variable are almost same but only one difference that is scope of variable can be controlled by user in extern variable.

Global variable

global variable is a variable that is defined outside of all functions and it is available to all functions.
These variables are unaffected by scopes and are always visible to functions and files, which means that a global variable exists until the program ends.

global variable are variables which are declared above the main( ) function. These variables are accessible throughout the program. They can be accessed by all the functions in the program. Their default value is zero.

Extern Variable

It is possible to create a global variable in one file and access it from another file. In order to do this, the variable must be declared in both files, but the keyword extern must precede the "second" declaration.
A particular extern variable can be declared many times but we can initialize at only one time


example 1:for global variable

file1.c
#include<stdio.h>
int a;    //global variable

main ()
{

a=10;
printf("a is %d",a);
foo();
}

file2.c
foo()
{
printf("a is in foo function  %d",a)
}


output :
a is  10
a is in foo function 10



example 2:for Extern variable

file1.c
#include<stdio.h>
int a=10;
main ()
{
extern int a;
//a=10;  you can't initialize hear it will give error
printf("a is %d",a);
foo();
}


file2.c
foo()
{
extern int a ;
printf("a is in foo function  %d",a)
}




output :
a is  10
a is in foo function 10



Comments

Popular posts from this blog

CAN INTERVIEW QUESTIONS

Qualifiers and Modifier in C

RTOS Real time operating system interview questions

CAN INTERVIEW QUESTIONS 2

What is UDS protocol

Memory mapping in c

TOP IOT PLATFORMS