Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If left to right and right to left - both associativity of operator are present in a statement then What will be considered? [duplicate]

int i=-1;
int a=65;
int b=a*i + ++i;

What is the value of b? Here associativity of =,+ is left to right and associativity of *,prefix increment (++) is right to left.

So What order of evaluation should I consider for int b=a*i + ++i;

left to right? right to left? Why?

like image 338
Abdus Sattar Bhuiyan Avatar asked Mar 19 '14 17:03

Abdus Sattar Bhuiyan


1 Answers

Do not think about assosiativity. Think about order of evaluation and unfortunately it is undefined in this case.
In the expression

int b=a*i + ++i;   

you are modifying i as well as using it in the same expression which invokes undefined behavior.

C99 states that:

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.

Further I would suggest you to read c-faq: Q 3.8.

like image 157
haccks Avatar answered Sep 21 '22 18:09

haccks