Search code examples
c++staticcoutostreamoperator-precedence

What is the difference in printing a function with a static int with one std::cout and multiple std::cout?


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;
}

Solution

  • 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.