Martian
Martian

Reputation: 94

Wrong output using g++ on linux and correct on windows

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?

Upvotes: 1

Views: 372

Answers (1)

Martian
Martian

Reputation: 94

After help from the comments I understood that the problem had to do with how the code executes in different compilers, I managed to solve the "bug" by explicitly calling the function f(), execute it's commands first, and then getting the return value. I explained it as good as I could so here is the code:

int main() { 
    cout << " x = " << x << endl; 
    int temp=f();
    cout << "1st output of f() " << temp << endl;
    temp=f();
    cout << "2nd output of f() " << temp << endl;

    return 0;
} 

Upvotes: 1

Related Questions