I came across this rather vague behavior when messing around with code , here's the example :
#include <iostream>
using namespace std;
int print(void);
int main(void)
{
cout << "The Lucky " << print() << endl; //This line
return 0;
}
int print(void)
{
cout << "No : ";
return 3;
}
In my code, the statement with comment //This line
is supposed to print out
The Lucky No : 3
, but instead it was printed No : The Lucky 3
. What causes this behavior? Does this have to do with C++ standard or its behavior vary from one compiler to another?
print
function is a nice example of a function with side-effects. Besides calculating a return value, it also changes global program state. Such functions are usually more difficult to reason about. Generally, strive towards functions that either compute a value or change state, but not both simultaneously. – Eneidaenema