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.
- #include <iostream>
- using namespace std;
- void withoutStatic(){
- int count=0;
- count++;
- cout<<count<<" ";
- }
- int main(){
- for(int i=0;i<5;i++)
- withoutStatic();
- return 0;
- }
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:
- #include <iostream>
- using namespace std;
- void withStatic(){
- static int count=0;
- count++;
- cout<<count<<" ";
- }
- int main(){
- for(int i=0;i<5;i++)
- withStatic();
- return 0;
- }
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