What are local, static and global variables in C?

Local, Static and Global variables:

Local variables:

Those variables whose existence is known only either to main() function or a function in which they are defined are called local variables. Local variables are declared with in the main program or a function.

Global variables:

Those variables whose existence is known to the both main() as well as other functions are called global variables. Global variables are declared outside the main() and other functions.

Example Program illustrating the concept of both local as well as global variables shown below.

Below program does not accept anything from the keyboard. It initialises the variables a to 10 outside the main() function and value().

 int a = 10;   /* global declaration */  
 int b;  
 printf(" = %dn" , i);  
 b = value(i)  
 printf(" j = %dn");  
 }         /* End of main() */  
          /* Function to compute value */  
 int value(i)  
 int i;  
 int c;  
 c = i + 10;  
 }        /* End of Function */  

i = 10
b = 20

The statement int  i = 10;   that appears before the main() is a global declaration. The value of i is accessed by the main program as well as the function value(). The variable c is local to the function value(). It has no existence in the function value(). The variable is also local to the main() but has no scope in the function value().

What are static variables?

Static variables are the variables which retain their values between the function calls. They are initialized only once their scope is within the function in which they are defined.

This entry was posted in C Programming. Bookmark the permalink.