C Language: Storage classes 3

Static storage classes.

The keyword “static” is used to declare variables of static storage class.

Example:

static int i;

Properties

Storage Memory
Default initial value Zero
Scope Local to the block in which the variables is defined.
Life Value of the variable persists/remains between different function calls.

Example:1

#include<stdio.h>
void abc()
{
  auto int a=10;
  printf("%d\n",a);
  a=a+10;
}
int main()
{
  abc();
  abc();
  abc();
  return(0);
}
/* Output */
10
10
10

Example:2

#include<stdio.h>
void abc()
{
static int a=10;
printf("%d\n",a);
a=a+10;
}

int main()
{
abc();
abc();
abc();
return(0);
}
/* Output */
10
20
30

Example:3

#include<stdio.h>
void abc()
{
static int a;
printf("%d\n",a);
a=a+10;
}

int main()
{
abc();
abc();
abc();
return(0);
}
/* Output */
0
10
20

Example:4

#include<stdio.h>
int main()
{
static int a=-5;
while(a)
{
  printf("%d\n",a);
  a++;
  main();
}
return(0);
}
/* Output */
-5
-4
-3
-2
-1

Like auto variables, static variables are also local to the block in which they are declared.

The difference between them is that static variables don’t disappear when the function is no longer active. Their values persist. If the control comes back to the same function again the static variables have the same values they had last time around.

NOTE: We should avoid using static variables unless we really need them. Because their values are kept in memory when the variables are not active, which means they take up space in memory that could otherwise be used by other variables.

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects