In this website, in the last section, they have provided f(i = -1, i = -1) as an example of undefined behavior due to unsequenced evaluation of subexpressions within function arguments. But since there is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call, f will always be called with (-1, -1) and i will be assigned -1. Is there any possibility of this not happening?
2 Answers
... there is a sequence point after the evaluation
Indeed. After the evaluation, so it does no good. The problem here is that there are two unsequenced side effects on i before the sequence point. It's formally UB.
3 Comments
Sourav Kannantha B
If there were different values being assigned to i, then it would be undefined since value of i cannot be foreseen... But in this case, i would always evaluate to -1.. Isn't it
Lundin
@SouravKannanthaB No, the value doesn't matter. Suppose we have some exotic scenario where
i is a volatile hardware register and every write to it makes something happen in hardware. It is not well-defined if, when or how many times this code will write to that hardware register.Lundin
@SouravKannanthaB In a more realistic example, like a mainstream x86 PC compiler, it will likely try to do something seemingly useful out of the situation and very likely just pass along the value -1. But there are no guarantees of any particular behavior, just a quality of implementation issue beyond the scope of the C language.
It's undefined behavior because the standard says it. Modifying a variable without a sequence point between the modifications is UB. There is no "unless both modifications set the same value" exception to the rule.
2 Comments
Sourav Kannantha B
So you mean 'with this particular values' this may result in expected behavior, but a similar expression with two different values would result in undefined behavior. Sure...
Ian Abbott
@SouravKannanthaB No, it means: "There is no [...] exception to the rule."
i(a global variable?)