Reputation:
What will the below program print?
#include <iostream>
using namespace std;
static int x = 10;
void main1()
{
cout << x << endl;
x = x + 1;
}
int main()
{
main1();
main1();
cout << x << endl;
}
As per my understanding, the above program we used static variable, so x
retains the last initialized variable. So the output will be
10
11
12
but if we removed static, we should get
10
10
10
but I am getting the below output, even after removing static.
10
11
12
Please help me to understand.
Upvotes: 0
Views: 77
Reputation: 1
the static keyword has several meanings in C depending on where yoi use it. Read this http://msdn.microsoft.com/en-us/library/s1sb61xd(v=vs.80).aspx
Upvotes: 0
Reputation: 1992
Since x is global visible to both main1 and main it will not make difference whether static is there or not.
Upvotes: 0
Reputation: 8886
Even if int x
is not static, it is still a global variable, outside the scope of main
and main1
.
Thus whatever change you make to x from anywhere inside this file is going to change it permanently.
Upvotes: 7