Scope and Lifetime of a variable
Scope and Lifetime of a variable
You will learn about scope and lifetime of local and global variables in this tutorial. Also, you will learn about static and register variables.
Posted By Manisha Gupta
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of a variable. And, storage class determines the scope, visibility and lifetime of a variable.
There are 4 types of storage class:
- automatic
- external
- static
- register
Local Variable
The variables declared inside the function are automatic or local variables.
The local variables exist only inside the function in which it is declared. When the function exits, the local variables are destroyed.
int main() { int n; // n is a local variable to main() function ... .. ... } void func() { int n1; // n1 is local to func() function }
In the above code, n1 is destroyed when
func()
exits. Likewise, n gets destroyed when main()
exits.Global Variable
Variables that are declared outside of all functions are known as external or global variables. They are accessible from any function inside the program.
Example 1: Global Variable
#include <stdio.h>
void display();
int n = 5; // global variable
int main()
{
++n; // variable n is not declared in the main() function
display();
return 0;
}
void display()
{
++n; // variable n is not declared in the display() function
printf("n = %d", n);
}
Output
n = 7
Suppose, a global variable is declared in
file1
. If you try to use that variable in a different file file2
, the compiler will complain. To solve this problem, keyword extern
is used in file2
to indicate that the external variable is declared in another file.Register Variable
The
register
keyword is used to declare register variables. Register variables were supposed to be faster than local variables.
However, modern compilers are very good at code optimization and there is a rare chance that using register variables will make your program faster.
Unless you are working on embedded systems where you know how to optimize code for the given application, there is no use of register variables.
Static Variable
A static variable is declared by using keyword
static
. For example;static int i;
The value of a static variable persists until the end of the program.
Example 2: Static Variable
#include <stdio.h>
void display();
int main()
{
display();
display();
}
void display()
{
static int c = 0;
printf("%d ",c);
c += 5;
}
Output
0 5
During the first function call, the value of c is equal to 0. Then, it's value is increased by 5.
During the second function call, variable c is not initialized to 0 again. It's because c is a static variable. So, 5 is displayed on the screen.