Wednesday, April 6, 2016

Static Keyword



“Static” keyword has two meanings, depending onwhere the static variable is declared :


  • Outside a function, static variables/functions only visible within that file, not globally (cannot be extern’ed) .

  • Inside a function, static variables: 
  1. Still local to that function.
  2.   Initialized only during program initialisation.
  3.  Do not get reinitialized with each function call .


Example 1 : 



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
   #include <stdio.h>

void counter()
{
 static count=0;
  count++;
  printf("%d\n",count);
}

int main()
{
 for(int i=0;i<5;i++)
 {
   counter();
 }
   return 0 ;
   }

   


Output: 
1
2
3
4
5


Example 2 : 


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
 #include <stdio.h>

void counter()
{
 int count=0;
  count++;
  printf("%d\n",count);
}

int main()
{
 for(int i=0;i<5;i++)
 {
   counter();
 }
   return 0 ;
   }



Output : 
1
1
1
1
1


Share this

0 Comment to "Static Keyword"

Post a Comment