Monday, January 16, 2012

static variable

static variable is a variable that has been allocated statically — whose lifetime extends across the entire run of the program. If no initial value have been provided when declare it, it will be initialized for you.

Example:
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

void sub();

int _tmain(int argc, _TCHAR* argv[])
{
 cout << "First run - " << endl;
 sub();
 cout << "Second run - " << endl;
 sub();

 system("PAUSE");
 return 0;
}

void sub(){
 int i;
 static int statici;

 cout << "before assign in sub()" << endl;
 cout << "i = " << i << endl;
 cout << "statici = " << statici << endl;

 i = 1;
 statici = 2;

 cout << "after assign in sub()" << endl;
 cout << "i = " << i << endl;
 cout << "statici = " << statici << endl;
 cout << endl;
}


Example of static variable

No comments:

Post a Comment