2

Here is the code

int main()
{
  int x=15;
  printf("%d %d %d %d",x=1,x<20,x*1,x>10);
  return 0;
}

And output is 1 1 1 1

I was expecting 1 1 15 1 as output,

x*1 equals to 15 but here x*1 is 1 , Why ? Using assignment operator or modifying value inside printf() results in undefined behaviour?

udit043
  • 1,610
  • 3
  • 22
  • 40
  • You explicitly set `x=1`. I'm not sure what else you would expect. – larsks Jul 23 '15 at 16:15
  • While not a direct duplicate of the **question**, the answers at [Why are these constructs using pre and post-increment undefined behavior?](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior/) do address this too in in-depth. – Antti Haapala -- Слава Україні Aug 17 '19 at 08:14

3 Answers3

7

Your code produces undefined behavior. Function argument evaluations are not sequenced relative to each other. Which means that modifying access to x in x=1 is not sequenced with relation to other accesses, like the one in x*1. The behavior is undefined.

Once again, it is undefined not because you "used assignment operator or modifying value inside printf()", but because you made a modifying access to variable that was not sequenced with relation to other accesses to the same variable. This code

(x = 1) + x * 1

also has undefined behavior for the very same reason, even though there's no printf in it. Meanwhile, this code

int x, y;
printf("%d %d", x = 1, y = 5);

is perfectly fine, even though it "uses assignment operator or modifying value inside printf()".

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
3

Within a function call, the function parameters may be evaluated in any order.

Since one of the parameters modifies x and the others access it, the results are undefined.

dbush
  • 205,898
  • 23
  • 218
  • 273
2

The Standard states that;

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

It doesn't impose an order of evaluation on sub-expressions unless there's a sequence point between them, and rather than requiring some unspecified order of evaluation, it says that modifying an object twice produces undefined behaviour.

Community
  • 1
  • 1
ameyCU
  • 16,489
  • 2
  • 26
  • 41