2

Will the right side of the expression get evaluated first or the left ?

void main ()
{
    int i = 0 , a[3] ;
    a[i] = i++;
    printf ("%d",a[i]) ;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

16

The order of evaluation of the operands of the assignment operator is unspecified: the operands may be evaluated in any order.

However, this expression (a[i] = i++) yields undefined behavior because you both modify i (using i++) and you separately read i (using a[i]) without a sequence point in between those actions.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • @msakr, i would be incremented at the end if there was something like a[k] = i++ ;. As James McNellis said, it's undefined behavior for a[i] = i++; due to no sequence points between the actions. – Kizaru Sep 19 '10 at 22:39
  • 2
    @msakr: C standard §6.5/2: "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 read only to determine the value to be stored." – Jonathan Leffler Sep 19 '10 at 22:45
  • @msakr: Concerning the order of evaluation, see C99 Appendix J ("Unspecified Behavior"): "The order in which subexpressions are evaluated and the order in which side effects take place, except as specified for the function-call `()`, `&&`, `||`, `?:`, and comma operators." Jonathan gives the quote that states that this particular expression yields undefined behavior. – James McNellis Sep 19 '10 at 22:45
  • @msakr: The source would be the list of sequence points as given in the C standard. – Oliver Charlesworth Sep 19 '10 at 22:46
  • @James : ` ...because you both modify i (using i++) and you read i (using a[i]) without a sequence point...`. The expression `b += a += b` does not invoke UB even though `b` is being read and modified without a sequence point. `a[i] = i++` invokes UB because the `prior value shall be read only to determine the value to be stored` rule is violated. Please correct me if I am wrong. – Prasoon Saurav Sep 20 '10 at 04:59
  • @Prasoon: That is correct. Jonathan in a comment to this answer and sysenter in his answer both quote that part of the standard. – James McNellis Sep 20 '10 at 13:27
3

C does not define which side gets evaluated first. The standard states (C99 §6.5/2):

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

The aforementioned result you posted is thereby UB.

sysenter
  • 39
  • 3