- Outside a function, static variables/functions only visible within that file, not globally (cannot be extern’ed) .
- Inside a function, static variables:
- Still local to that function.
- Initialized only during program initialisation.
- 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
0 Comment to "Static Keyword"
Post a Comment