0

So when I have this function, and I print it to the console via multiple statements, I get the expected results:

0

1

But when I print the function out through just one cout statement on the same line, I get:

3 2

(This is after the initial 0 and 1 that were previously printed)

Why does it print backwards?

#include "stdafx.h"
#include <iostream>

using namespace std;

int addOne()
{
    static int s_num = -1;
    return ++s_num;
}

int main()
{
    cout << addOne() << "\n";
    cout << addOne() << "\n";
    cout << addOne() << " " << addOne() << "\n";

    return 0;
}
curiousguy
  • 7,344
  • 2
  • 37
  • 52
  • 2
    Possible duplicate of [cout << order of call to functions it prints?](https://stackoverflow.com/questions/2129230/cout-order-of-call-to-functions-it-prints) – demogorgon Jun 27 '18 at 02:45

1 Answers1

-1

You are actually stumbling on unspecified behavior. In this context, and any other such context where the operators are of the same precedence, the function calls can be evaluated in any order. In this case, the compiler chose to evaluate the second function call before the first, but other compilers might do it differently.

meat
  • 589
  • 2
  • 8
  • 3
    This is unspecified behavior, not undefined behavior. Unsequenced modifications in the same memory location cause undefined behavior, but function calls like `addOne()` within the same full-expression are at worst indeterminately sequenced. – aschepler Jun 27 '18 at 02:47
  • Thanks - it is what I had meant but I'm afraid I slipped up on the term. Corrected. – meat Jun 27 '18 at 02:52
  • 1
    @aschepler This *was* unspecified behaviour, until C++17 – M.M Jun 27 '18 at 04:20
  • How is precedence relevant here? – curiousguy Jun 28 '18 at 00:15