2

If I call a function, that changes value of a variable, in std::cout and try to print that value then std::cout prints old value. Why?

If I try to output that value in the next cout-call, it'll print updated value.

#include <iostream>
int reset(int& v)
{
   v = 0;
   return 0;
}
int main()
{
   int i = 5;
   std::cout << reset(i) << " " << i; //output: 0 5
}

Expected output: 0 0

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Shikhali
  • 29
  • 2
  • 3
    Good clear question (and hard to know it's a duplicate until you know the answer). Almost certainly a good duplicate out there so I'll avoid an answer. In short `<<` is no more than syntactic sugar for some function calls, and the order of evaluation of the function arguments is unspecified by the standard. Note that C++17 and onwards defines this. – Bathsheba Oct 16 '19 at 08:08
  • [Can't reproduce](https://onlinegdb.com/SkenGlUVKB). – Blaze Oct 16 '19 at 08:09
  • Notice that behavior would be what you expected since C++17. – Jarod42 Oct 16 '19 at 08:09
  • @Blaze: try with older standard than C++17. – Jarod42 Oct 16 '19 at 08:11
  • 1
    @Jarod42 the C++ tag info says "Unless the question explicitly mentions which version of the C++ standard that is used, it is assumed that the current version is used.". To avoid confusion, there are additional tags for old versions. If OP wants to compile for an old version of the language, it would be helpful if he would at least mention which version that is. – Blaze Oct 16 '19 at 08:14
  • Sorry, my bad. I'm using C++11 – Shikhali Oct 16 '19 at 08:15
  • @Blaze: Personally I think C++11 is the "default" standard. Has been for a few years on this site. Perhaps I'm wrong on this now though and we should think of C++17 being the default (although I conject that a minority of codebases conform to C++17). – Bathsheba Oct 16 '19 at 08:17
  • And whereas we know the "issue", it is simpler to know which standard is affected. – Jarod42 Oct 16 '19 at 08:20
  • @Bathsheba yeah, that's possible. I guess OP also can't be expected to know that the issue is related to standard versions. – Blaze Oct 16 '19 at 08:21

0 Answers0