C - Programming#1 Storage Class

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;
}
content of otherFile.c
int var=5;

output of the code: 5//it works perfectly.

NOTE: what will happen if the otherFile.c has line int var=5 commented, means there is no definition of the var variable exists?
Ans: Compiler will believe that the var is defined somewhere but when during execution it comes to the linker and it doesn't find its definition it throws an error.

in main.c file if we write 
extern int var;
extern int var;
extern int var;
instead of writing only once, then it is also allowed because in c multiple declarations are allowed but multiple definitions are not allowed.

ex-2:
#include<stdio.h>
int var=10;
int main(){
extern int var;
printf("%d",var);
return(0);
}
what will be its output?
Ans: extern variable simply tells to the compiler that the variable is defined outside of my declaration scope, go out of my declaration scope and find the variable definition whether it could be in the same file or the other file. Hence this code will work and the output: 10

ex-3:
#include<stdio.h>
extern int var=10;
int main(){
printf("%d",var);
return(0);
}
output: 10//because the declaration and definition are both together.

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;
}
If we don't initialize these variables then they by default initialized by the compiler with some garbage value. However, if we don't initialize the global auto variable then it will be by default initialized to zero by the compiler



Comments