Based on the scope and lifetime of a variable, variables are categorized into two types
- Local variables
- Global variables
“Scope,” tells about visibility (i.e., from where and all places the variable is visible), whereas “lifetime,” tells about durability (till how much time the value in the variable is valid).
What is the local variable?
The variables declared inside a function is known as local variable.
- The scope of local variables is throughout the block, i.e., we can’t access a local variable from outside the “block” in which we declared it.
- A lifetime of a local variable is throughout the function, i.e., memory to the local variables allocated when the Execution of a “function” is started and will become invalid after finishing the Execution of a function.
For local variables, memory is allocated in the “stack” when a call to the function is made and will get deallocated when the function returns back to the caller.
For example, the below local variable (a = 10) cannot be accessed from the fun( ) because it is local to the main( ). Hence, we will get a compilation error.
#include <stdio.h>
void main()
{
// Local variable
int a = 10;
printf("Printing in main %d", a);
}
void fun()
{
// compilation error, because a is local to main and
// cannot be accessed from inside this function.
printf("Printing in fun %d", a);
}
Example #1
The below program will give a compilation error because the scope of the local variable starts from the point where we declared.
In the below example, we are trying to access a global variable before we are declaring it, so we get the compilation error.
#include <stdio.h>
int main()
{
printf("%d", value);
int value; // Scope is from this point to end of the block
return 0;
}
Example #2
Multiple declarations of local variables with the same name and in the same scope are not allowed.
In the below example, we are trying to declare a Local variable with the same name more than once, so we will get compilation errors.
#include <stdio.h>
int main()
{
int value = 10;
int value = 20;
printf("%d", value);
return 0;
}