The static and non-static variables
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info:
To do: Display some integers
To show: The static and non-static variables
// Demonstrates the static and non-static variable
// The .h can be removed for C++
#include <iostream>
using namespace std;
int funcstatic(int)
{
// local variable should exist locally...
int sum = 0;
sum = sum + 10;
return sum;
}
int main(void)
{
int r = 5, s;
// test the function calls several times...
cout<<"Without static keyword\n";
cout<<"----------------------\n\n";
s = funcstatic(r);
cout<<"1st time function call, s = "<<s<<endl;
s = funcstatic(r);
cout<<"2nd time function call, s = "<<s<<endl;
s = funcstatic(r);
cout<<"3rd time function call, s = "<<s<<endl;
return 0;
}
Output example:
Without static keyword
----------------------
1st time function call, s = 10
2nd time function call, s = 10
3rd time function call, s = 10
Press any key to continue . . .
Change the following code:
int sum = 0;
to
static int sum = 0;
and
cout<<"Without static keyword\n";
to
cout<<"With static keyword\n";
Rebuild and rerun the program. The following output should be expected.
With static keyword
-------------------
1st time function call, s = 10
2nd time function call, s = 20
3rd time function call, s = 30
Press any key to continue . . .