Monday, February 5, 2018

Coding using keywords- part 7 (static)

After explaining auto, register, and extern keywords; the last storage class is static.



Briefly, static is used to allocate a variable only one time in the RAM. In other word, any change for this variable will be executed only in one place in the RAM. To see the difference, I will take two example; one without static and the other with it.

  1. #include <iostream>  
  2. using namespace std;  
  3. void withoutStatic(){  
  4.     int count=0;  
  5.     count++;  
  6.     cout<<count<<" ";  
  7. }  
  8. int main(){  
  9.     for(int i=0;i<5;i++)  
  10.         withoutStatic();  
  11.     return 0;  
  12. }  

Output:

1 1 1 1 1

Explanation


Each time the function withoutStatic() is called the variable count is initialized by 0, incremented and showed on the screen. Now, let's see the other example:

  1. #include <iostream>  
  2. using namespace std;  
  3. void withStatic(){  
  4.     static int count=0;  
  5.     count++;  
  6.     cout<<count<<" ";  
  7. }  
  8. int main(){  
  9.     for(int i=0;i<5;i++)  
  10.         withStatic();  
  11.     return 0;  
  12. }  


Output:

1 2 3 4 5

Explanation


By using static, the variable count is found in only one place in the RAM. In opposite, in the first program each time the function withoutStatic() was called, a new variable is created in the RAM.

In other word, by using static incrementing count will be always done on the same variable which gives the output of above.

Note:

You can see all the rest parts of keywords in: https://philippebalech.blogspot.com

You can also check all the keywords in C: https://philippebalech.blogspot.com/2018/01/keywords-in-c.html

No comments:

Post a Comment