Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C/C++ is x[i] * y[i++] always equal to x[i] * y[i] [duplicate]

Possible Duplicate:
Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…)
increment values in printf

I have a two double arrays x and y and integer i. My question is whether the statement:

double res = x[i] * y[i++];

is always equal to the statement:

double res = x[i] * y[i];
i++;

Is it possible that some compilers would change x[i] * y[i++] into y[i++] * x[i], which obviously produces different result?

like image 223
Serg Avatar asked Dec 05 '12 18:12

Serg


2 Answers

No -- x[i] + y[i++] has undefined behavior. You're modifying the value of i and also using the value i without an intervening sequence point, which gives undefined behavior1.


  1. In C++11 the standard has eliminated the "sequence point" terminology, but the effect remains the same -- the two are unordered with respect to each other.
like image 147
Jerry Coffin Avatar answered Oct 19 '22 15:10

Jerry Coffin


No, it is undefined when the increment occurs.

like image 8
Lindydancer Avatar answered Oct 19 '22 17:10

Lindydancer