C - Use static variables

Introduction

Variables used within a function are local to that function.

Their values are used and then discarded when the function is done.

Demo

#include <stdio.h> 

void proc(void); 

int main() { //from w w  w.j a v a  2  s.c  om
    puts("First call"); 
    proc(); 
    puts("Second call"); 
    proc(); 
    return(0); 
} 

void proc(void) { 
      int a; 

      printf("The value of variable a is %d\n",a); 
      printf("Enter a new value: "); 
      scanf("%d",&a); 
}

Variable a in the proc() function does not retain its value.

The variable is initialized only by the scanf() function.

Modify the source code:

Demo

#include <stdio.h> 

void proc(void); 

int main() { //from  w ww.  ja v a  2  s.c om
    puts("First call"); 
    proc(); 
    puts("Second call"); 
    proc(); 
    return(0); 
} 

void proc(void) { 
      static int a; //static is added

      printf("The value of variable a is %d\n",a); 
      printf("Enter a new value: "); 
      scanf("%d",&a); 
}

Result

Because the variable was declared as static, its value is retained between function calls.

You need to declare variables as static if you need their values retained every time the function is called.

Related Topic