Hello CodeForces. Today, I was solving AtCoder's 700 point problem and faced with an unfamiliar situation. After some analysis, surprisingly, I found that C++ reads the lines from the back.
For example, see this code: https://ideone.com/VHnIIj
I call the function "add1" before "add2" but it seems that the code reads it in reversed order.
I googled it and couldn't find any proper information about that. Can someone share his/her thoughts, please?
Edit; Thank you all for the response. It's clear to me now.
I know that in some operators, the order of calculation is not defined. Most probably this is the case. So I think, that there is no reversed order, but in this particular case compiler makes the order like this. But if you change code and make for example not two function calls, but 3 , 4 or 5. The order will be others.
Order of evaluation
From cppreference :-
Order of evaluation of the operands of almost all C++ operators (including the order of evaluation of function arguments in a function-call expression and the order of evaluation of the subexpressions within any expression) is unspecified. The compiler can evaluate operands in any order, and may choose another order when the same expression is evaluated again.
You should avoid using C++ operators to write an expression whose result depends on the order in which its operands are evaluated.
You can alway use the semicolon statement terminator or the comma operator to specify the order in which a sequence of computational tasks are performed so that no race situation takes place among related operands when the order of evaluation may change the result of an expression or the program behavior in general due to interpdendence.
For example, your code can be rewritten as:
The comma operator in the variable declaration statement instructs the compiler to generate an object code that initializes the sequence of variables
x
,x1
andx2
in the same order they are declared in the source code, i.e. the generated object code should execute the following ordered sequence of computational tasks:Initialize
x
to 0.Call
add1( x )
, and initializex1
to the return value of such function call.Call
add2( x )
, and initializex2
to the return value of such function call.Finally, the
cout << x1 << " " << x2 << endl
statement written in terms of the overloaded binary operator<<
is translated to a sequence of function calls to produce the desired program output functional behavior. In this case, the program output is race free.The following is the expected result. Further information about race condition in shared-memory applications is available in Wikipedia