3

I have this small programm:

 #include <iostream>
using namespace std;

int f ();
int g();

int main () {
    cout << f() << f() << g();
}

int f () {
    static int zahl = 3;
    return ++zahl;
}

int g () {
    return f();
}

It prints out 654, but I expected 456, and I have no idea why it does that. Can anyone explain?

Lasse Meyer
  • 1,429
  • 18
  • 38
  • 8
    The order of evaluation is unspecified in C++: the compiler is free to execute the calls to `f()` and `g()` in any order it wants. – Dietmar Kühl Jul 21 '14 at 14:00
  • Ok, thanks. I'll have to put in seperate lines then, or is there a other way to do it? – Lasse Meyer Jul 21 '14 at 14:04
  • Related: [The order of cout messages is not as expected](http://stackoverflow.com/questions/23309153/the-order-of-cout-messages-is-not-as-expected), [C++: The order of std::cout](http://stackoverflow.com/questions/20123196/c-the-order-of-stdcout), [cout << order of call to functions it prints?](http://stackoverflow.com/questions/2129230/cout-order-of-call-to-functions-it-prints) – crashmstr Jul 21 '14 at 14:04
  • 1
    @ecatmur: although it is unlikely that `g()` would be evaluated between the two calls to `f()` I'm not aware of any constraint restricting the possible order of function parameter evaluations. I don't think there is a restriction that arguments to a nested function call are evaluated together. – Dietmar Kühl Jul 21 '14 at 14:12

0 Answers0