I have this c++ piece of code which I wrote in CodeBlocks:

#include <iostream>
using namespace std;
double square(double arg) {
    cout<<"double ";
   return arg * arg;
}
int square(int arg) {
    cout<<"int ";
   return arg * arg;
}
int main(void) {
   cout << square(2) << " " << square(2.) << " " << square('A') << endl;
   return 0;
}

For some reason the print is: int double int 4 4 4225 instead of: int 4 double 4 int 4225

I tried compiling in Visual Studio Code's C++, but I still get int double int 4 4 4225. The code seems to print properly on online compilers.

1

There are 1 best solutions below

0
Jarod42 On

Prior C++17, evaluation order for operands of operator << is unsequenced.

so, in

std::cout << " " << square(2.)

square(2.) might be evaluated (with its printing side-effect) before std::cout << " ".

Since C++17, new rules has been added to have "expected" behavior:

  1. In a shift operator expression E1 << E2 and E1 >> E2, every value computation and side effect of E1 is sequenced before every value computation and side effect of E2.