I am learning c++ and decided to write a small program to practice on variable scopes. The problem is that I am getting a different (and wrong in my opinion) output on Linux after compiling and executing, while on windows everything is correct. Here is the code:
/*main.cpp*/
#include <iostream>
using namespace std;
extern int x;
int f();
int main() {
cout << " x = " << x << endl;
cout << "1st output of f() " << f() << endl;
cout << "2nd output of f() " << f() << endl;
return 0;
}
/*f.cpp*/
#include<iostream>
using namespace std;
int x = 10000;
int f() {
static int x = ::x;
{
static int x = 8;
cout << x++ << endl;
}
cout << x++ << endl; return x;
}
the command I am typing on linux is $g++ main.cpp f.cpp && ./a.out
Desired output (windows output):
x = 10000
8
10000
1st output of f() 10001
9
10001
2nd output of f() 10002
Given (Linux) output:
x = 10000
1st output of f() 8
10000
10001
2nd output of f() 9
10001
10002
As I can tell it seems like the Linux program skips the cout of the int f() function, any ideas why such a thing happens?