C language order of precedence

184 views Asked by At
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?

1

There are 1 answers

4
Sourav Ghosh On

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.