0

The program below outputs 10. I expected it to first print 0 (the else branch of function f) and then to print 1. How come that the order is reversed?

#include <iostream>     
using namespace std;

int f(bool& b){
    if (b==true){
        return 1;
    } else {
        b=true;
        return 0;
    }
}

int main () {
    bool b=false;
    cout<<unitbuf<<f(b)<<unitbuf<<f(b);

  return 0;
}

The output

10
Slazer
  • 4,100
  • 7
  • 25
  • 53

1 Answers1

5

The order of evaluation of arguments to a function is unspecified. So, you have this argument on the left:

(cout << unitbuf << f(b) << unitbuf)

And this one on the right:

f(b)

Both being passed to operator<< (the last one). Either one can be evaluated first. If the one on the left is evaluated first, then the call to f(b) on the left will happen first, and return 0. Then the one on the right will be called and return 1, resulting in an output of 01. If the one on the right is evaluated first, then it will return 0, and the one on the left will then be called, returning 1, resulting in the reversed output of 10.

Benjamin Lindley
  • 95,516
  • 8
  • 172
  • 256
  • I think the reason is not really "the order of evaluation of arguments to a function", but rather "the order of evaluation of the operands in an expression". Because "cout << f(b) < – zentrunix Aug 07 '13 at 03:01