Local, Global and Static variable in C programming language | Coding classpoint

Local, Global and Static variable


Local variable:

Variables that are defined with in a body of function or block. The local variables can be used only in that function or block in which they are declared. 

Same variables may be used in different functions such as

function() 
 int a,b; 
function 1(); 
function2 () 
int a=0; 
b=20;
 }

Global variable:

The variables that are defined outside of the function is called global variable. All functions in the program can access and modify global variables. Global variables are automatically initialized at the time of initialization.

Example: 

#include 
void function(void); 
void function1(void); 
void function2(void); 
int a, b=20; 
void main() 

printf(“inside main a=%d,b=%d \n”,a,b); 
function(); 
function1(); 
function2();
 }
 function() 

Prinf(“inside function a=%d,b=%d\n”,a,b);
 } 
function 1() 
prinf(“inside function a=%d,b=%d\n”,a,b); 
function 2() 
prinf(“inside function a=%d,b=%d\n”,a,); 
}

Static variables: 

Static variables are declared by writing the key word static.

syntax:

static data type variable name; 
static int a; 

-the static variables initialized only once and it retain between the function call. If its variable is not initialized, then it is automatically initialized to zero.

Example: 

void fun1(void); 
void fun2(void); 
void main() 
fun1(); 
fun2(); 
void fun1() 
int a=10, static int b=2; 
printf(“a=%d, b=%d”,a,b); 
a++; b++; 

Output:

a= 10 
b= 2 
a=10 
b= 3 


Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.