Overall statement:
print(x, x++);
leads to undefined behavior . Once a program has Undefined Behavior, it ceases to be a valid C ++ program, and literally any behavior is possible. Therefore, it makes no sense to find reasoning for such a program.
Why is this behavior undefined?
Allows you to evaluate the program step by step to such an extent that we can, without a doubt, prove that it causes Undefined Behavior .
The evaluation order of the arguments to the Unspecified [Ref 1] function.
Unspecified means that implementations are allowed to implement this particular functionality at their discretion, and there is no need to document details about it.
Applying the above rule to a function call:
print(x, x++);
An implementation can evaluate this as:
- From left to right or
- Right left or
- Any magic order (in the case of more than two function arguments)
In short, you cannot rely on an implementation to follow any particular order, because it is not required by the C ++ standard.
In C / C ++, you cannot read or write a variable more than once without an intermediate point [Ref 2] . If you do this, it will result in an Undefined Behavior. Regardless of whether one of the arguments is evaluated first in the specified function, there is no sequence point between them, the sequence point exists only after evaluating all the arguments of the function [Ref 3] .
In this case, x
accessed without an intermediate point in the sequence and, therefore, leads to Undefined behavior.
Simply put, itβs better to write any code that doesnβt call such Undefined Behaviors , because after that you cannot expect any specific behavior from such a program.
[Ref 1] C ++ 03 Standard Β§5.2.2.8
Paragraph 8:
[...] The procedure for evaluating function arguments is not specified . [...]
[Ref 2] C ++ 03 5 Expressions [expr]:
Paragraph 4:
....
Between the previous and next points in the sequence, the scalar object must have the value of the stored value, changed no more than once by evaluating the expression. In addition, the previous value should only be accessed to determine the value to be stored . The requirements of this section are satisfied for each admissible ordering of the subexpressions of the full expression; otherwise, the behavior is undefined .
[Link 3] C ++ 03 1.9 Execution of the program [intro.execution]:
Paragraph 17:
When a function is called (regardless of whether the function is built-in), a sequence point appears after evaluating all the arguments of the function (if any), which is performed before any expressions or operators are executed in the function body.