1

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?

jww
  • 97,681
  • 90
  • 411
  • 885
Martian
  • 94
  • 1
  • 9
  • 1
    Possible duplicate of https://stackoverflow.com/q/2934904/1171191 – BoBTFish Oct 28 '19 at 11:51
  • 1
    As you can see nothing is skipped, only the "... output of f()" part is output at different times. – rustyx Oct 28 '19 at 11:55
  • 1
    Remember that all operator overloading is implemented as functions and functions calls. When you use e.g. `<<` what you're really doing is calling a function called `operator<<`, passing the stream and the value you print as arguments. And the problem is that the evaluation order of arguments is *unspecified* and could be different between compilers, as shown by your example. See e.g. [this evaluation order reference](https://en.cppreference.com/w/cpp/language/eval_order) for details. – Some programmer dude Oct 28 '19 at 11:57
  • thanks everyone, I see now. The problem was in the order of the execution of function f(); – Martian Oct 28 '19 at 12:01
  • 1
    Please place answers in Answer blocks. Later, you can accept your own Answer. Also see [How does accepting an answer work?](https://meta.stackexchange.com/q/5234/173448) – jww Oct 28 '19 at 12:22
  • related: https://stackoverflow.com/questions/52203232/disturbing-order-of-evaluation – YSC Oct 28 '19 at 12:48

1 Answers1

1

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;
} 
Martian
  • 94
  • 1
  • 9