extern storage class: Writing
int var;//declaration and definition
means telling the compiler about the declaration(telling the compiler about the type of variable) and the definition(telling the compiler to allocate the memory) of the variable of type int. But, when we write extern keyword before the variable name it just declares the variable and don't initialize it.
extern int var;//declaration only
When do we need it: when the programmer wants to access a variable from a file and the variable is defined in other file.
ex: let say we have two file main.c and otherFile.c
content of main.c
#include<stdio.h>
extern int var;//telling the compiler that this variable is defined in the other file.
int main(){
printf("%d", var);
return 0;
}
int var=5;
extern int var;
extern int var;
extern int var;
#include<stdio.h>
int var=10;
int main(){
extern int var;
printf("%d",var);
return(0);
}
#include<stdio.h>
extern int var=10;
int main(){
printf("%d",var);
return(0);
}
Auto storage class: variable defined in a scope are by default automatic variable. Once the program execution is complete these variables get destroyed automatically and hence the name automatic and this property is advantageous in the sense that the freed memory by these variables can be utilized by the some other variables. Writing auto before a variable name is equivalent to the not writing auto before variable name because compiler by default considers the variables as auto if there is nothing written before it.
ex:
#include<stdio.h>
int main(){
auto int var; or int var;
printf("%d", var);//works perfectly fine and prints some random value.
return 0;
}
Comments
Post a Comment