Click to See Complete Forum and Search --> : little question


VishalNikiSharma
March 3rd, 2003, 03:44 AM
Dear Friends
I like to know what will be the o/p of the following code


..........
a[i++] = 3;
.......

will the value of 3 goes in i before incrementing or after incrementing.



also another question is...........

is there is any difference in comma operator " , " when applied to c and when applied to c++
i got different answer in c and c++

Thanks in advance
vishal

Doctor Luz
March 3rd, 2003, 04:15 AM
i will be incremented after.

if i=2 for example. a[2]=3 is the result and then i will become 3;

Gabriel Fleseriu
March 3rd, 2003, 04:18 AM
a[i++] = 3; is equivalent to a.operator[](i++) = 3;As you know, the function arguments are fully evaluated before the function is entered, so i++ will be evaluated before assigning 3 to the array element. However, the "return value" of i++ is the previous value of i (because of the postincrement).

So, 3 goes to the i-th element, and i is incremented "afterwards". If a is an array of built-ins, or of objects that have a natural semantics of operator[], your code is equivalent to (in the absence of exceptions):

a[i] = 3;
++i;

If the operator[] has side effects, or throws an exception, the code snips are not equivalent.

I am not aware of any difference regarding the comma operator in C vs. C++, but I didn't think of this question in detail.