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

This

void func() { 
  static int i = 0; 
  cout << "i = " << ++i << endl; 
}

Is like this

static int i = 0; 
void func() { 
  cout << "i = " << ++i << endl; 
}

With the exception that the scope of the 'i' variable is just the function.

It allows you to create variables local to a function, but which preserve the last known value until the function is called again.

This is very useful for things like

static int initialised = 0;
if ( !initialised ) { doInit(); initialised = 1; }

Or

static int uniqueID;
return uniqueID++;
commented: TY for your help, Salem. +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.