1
a = 5;
c = (b =a+2) - (a=1);

In book c programming a modern approach by kn king it is written that the effect of executing the second statement will result in 6 or 2 as it is undefined behavior of c but in other books like c by Dennis it is written that it will be executed from left to right. Which one is correct?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Riya
  • 25
  • 3
  • 3
    it is undefined behavior. – BLUEPIXY Dec 26 '16 at 06:53
  • 2
    What the heck is "C by Dennis"? If you're talking about [K&R](https://en.wikipedia.org/wiki/The_C_Programming_Language), it doesn't say anything about left-to-right execution. – user2357112 Dec 26 '16 at 06:54
  • 2
    Are you sure King says that? Which edition and page number? – Keith Thompson Dec 26 '16 at 07:07
  • There is no guarantee that the result will be 6 or 2 — they're possible values of the result, but so are 0 and 256 and any other number. The code exhibits undefined behaviour. Search for 'nasal demons'. – Jonathan Leffler Dec 26 '16 at 07:46

1 Answers1

2

In the above case,

 c=(b=a+2) -(a=1);

the value of a is being changed and being read without a sequence point in between, so it is undefined behavior.

Quoting C11, Annex §J.2, Undefined behavior

A side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object.

Also related, from chapter §6.5

The grouping of operators and operands is indicated by the syntax.85) Except as specified later, side effects and value computations of subexpressions are unsequenced.86)

So, there's no guarantee which subexpression will get evaluated first.

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261