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

StackOverflow https://stackoverflow.com/questions/22513036

  •  17-06-2023
  •  | 
  •  

Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

here you should consider the operator precedence. here the expression is solved based on precedence of the operator so at a time only one associativity is applied.
The associativity comes into picture when the operator has same precedence and in that case associativity will be same.
In your question b=a*i + ++i i used twice results in undefined behavoiur.

otherwise it would be evaluated as,
++ followed by * then + operation according to precedence. if this was followed the the answer would be,

b=a*i + ++i
b=65*i + 0
b=65*0 + 0
b=0 + 0
b=0

but the compiler can use the stored value of i instead of using value after ++i,

b=a*i + ++i
b=a*-1 + 0
b=-65 + 0
b=-65

this results in undefined behaviour since b can be 0 or -65. and also you can see that associativity doesn't create problem while evaluating since operators with same precedence will have same associativity and evaluation is ordered by precedence first and within that ordered by associativity.

There are two things associativity and precedence .

First check precedence and then associativity.

In you expression int b=a*i + ++i;

++has higher precedence than + and * so first ++ would be evaluated. After that + and *, * has higher precedence so * is evluated. In the last + is evaluated.

It's also the case as haccks suggested, you should not modify and use the value in the same expression.(not a good practice)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top