wtorek, 8 grudnia 2015

C++ << operator evaluation order

Executing the code: with gcc compiler we receive:

 computing ... 
2 + 2 = 4
as expected. However, there is a pitfall as the behavior depends on the function parameter evaluation order. Let us investigate it in more details. First of all, the << operator is left-associative which means it is evaluated from left to right and the operator << is replaced with the equivalent function call (for more details and references please have a look at how does cout << actually work?). So, the line:
cout << "2 + 2 = " << foo() << endl;
might be seen as something like:
operator<<(operator<<(operator<<(cout, "2 + 2 = "), foo()),endl);
Now foo() is called before operator<<(cout, "2 + 2 = ") because of the right-to-left function parameter evaluation order. While the function parameter evaluation order is not defined by standard (again, see SO function parameter evaluation order question for more references), the code is in fact unsequenced and its behavior is undefined. Thus, it should be rather rewritten like:

Source details

The code comes from the simple console game where the foo() function was designed to execute the game itself and to return the game result to the main function of the program.