Sunday, June 1, 2008

Why doesn't the statement 'a[i] = i++;' work in C?

Question: Why doesn't the statement 'a[i] = i++;' work in C?

Answer: The reason for this statement to throw an error (or at least doesn't work uniformly) in C is that the same variable 'i' is being modified in the right side of the assignment as well as it is being referred to in the left side of the assignment, which C standards don't allow. The reason for not allowing such a statement is to avoid the ambiguity whether to have the original 'i' in the left side as the array subscript or to have the changed value of 'i'. C by K&R says that such a statement will have unspecified behavior, whereas the C Standard simply rules this out and says that such a statement is undefined.



Unknown said...

It's working

int main()
int a[10];
int i=0;
printf(" %d\n",a[i]);
return 0;

Geek said...

Hi Nilanjan,

Thanks for your inputs. The code might work for some compilers (I'm sure you already know that any standard C compiler is only bound to comply with all the defined behavior as given in the C Language Specification and hence they are free to implement anything out of scope the way they want), but as I have mentioned in the answer that the behavior is undefined (by Standard C) and hence it's not (or should I use 'might not be') uniform across all compilers which means it might work for few, might not work for others or might work differently for others.

BTW, would you like to share with us which compiler did you use and what values were displayed as output?

Since the usage is undefined by Standard C hence I think the usage should be strictly discouraged. After all, we have many other fully-defined ways of dealing with the same situation :-)