views:

162

answers:

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]) ;
}
+16  A: 

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
@mahmoudsakr: No, that is incorrect.
James McNellis
@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
@James: source?
msakr
@msakr: C standard §6.5/2: "Between the previous and next sequence point an object shall have its stored valuemodified at most once by the evaluation of an expression. Furthermore, the prior valueshall be read only to determine the value to be stored."
Jonathan Leffler
James McNellis
I stand corrected. a[i] = i++ does in fact yield UB.
msakr
@msakr: The source would be the list of sequence points as given in the C standard.
Oli Charlesworth
@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
@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
+3  A: 

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