1
int x;
int fun1()
{
    x=x+10;
    return x;
}
int main()
{
    x=5;
    cout<<x;
    cout<<fun1();
}

this produces 5 and 15 while

cout<<x<<fun1();

this produces 15 and 15. Please explain. Thankyou

Shyam
  • 89
  • 7
  • 2
    See this answer for the sequence of evaluation: http://stackoverflow.com/questions/10782863/what-is-the-correct-answer-for-cout-c-c – Gerriet May 04 '17 at 06:34
  • Insert newlines in your output for clarity. Right now the output will be e.g. 515 without \n. – Brandin May 04 '17 at 06:37
  • Maybe it will be clearer if you write out the actual [`operator <<`](http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2) invokes as they're defined. Try writing them as nested function calls. The selected answer for the question linked by Gerriet goes into detail in doing so. – WhozCraig May 04 '17 at 06:45

1 Answers1

0

In c++ reference, order of evaluation of arguments of std::cout is unspecified. It is not left-to-right, right-to-left, or anything else.

Please avoid this. Instead use separate calls.

see also

v78
  • 2,803
  • 21
  • 44
  • 1
    cout << a << b << c has a well-defined order. The problem is the function call, not the ordering per se. – Brandin May 04 '17 at 06:36
  • @Brandin, what about ``std::cout << c++ << c ;`` [link](http://stackoverflow.com/questions/10782863/what-is-the-correct-answer-for-cout-c-c) . Not function just call, but evaluations in general. – v78 May 04 '17 at 06:38
  • @BenjaminLindley, thanks. corrected the ambiguous sentence. – v78 May 04 '17 at 06:39