3

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?

8
  • Maybe the function changes i (a global variable?) Commented Feb 10, 2021 at 12:27
  • 1
    Maybe, but still won't it be defined behavior? Since at the end i will be 'definitely' having value assigned inside 'f' and not -1. Commented Feb 10, 2021 at 12:29
  • Just to be clear: the comma inside the function call is not a sequence point. Order of function parameter evaluation is unspecified, so this is indeed UB. Commented Feb 10, 2021 at 12:33
  • The linked answer has a (slightly contrived) example of what could go wrong. Commented Feb 10, 2021 at 12:34
  • @dratenik Given today's highly-pipelined CPUs that actually do execute multiple instructions in parallel, I wouldn't say the example is contrived in any way. Commented Feb 10, 2021 at 12:36

2 Answers 2

2

... 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.

Sign up to request clarification or add additional context in comments.

3 Comments

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
@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.
@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.
1

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

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...
@SouravKannanthaB No, it means: "There is no [...] exception to the rule."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.