I have been looking at a small bit of code concerning the use of static with variables; I thought I understood the use of static, but I find this code confusing:
//: C03:Static.cpp
// Using a static variable in a function
#include <iostream>
using namespace std;
void func() {
static int i = 0;
cout << "i = " << ++i << endl;
}
int main() {
for(int x = 0; x < 10; x++)
func();
}
The PDF explains that:
Each time func( ) is called in the for loop, it prints a different value.
If the keyword static is not used, the value printed will always be
‘1’.
So, each loop through the funct() using static will produce an incremented value, whereas not using static would cause it to always remain zero(0)?
I thought the use of static was to force the variable to remain constant, in this case, zero(0)? Each time the static variable is met it reads "0". I see that this does not make relative sense in relation to this code, but it seems in error to say the static affects it in this manner.
Maybe I am simply confused in some area of the definition and use of "static" for a variable and\ or how to make use of it.
Any and all help would be appreciated.
Thank-you in advance.
sharky_machine