Doubt c programming


18/19? if 19 plz explain

int main()

   int i = 4, ans;

    ans = ++i+ ++i + ++i;

    printf("%d\n", ans);

    return 0;


What is the output of this program


The correct answer in this case is 19.
This is because of the right to left associativity of the pre-increment operator.
Therefore the expression is evaluated as under:- (++i)+(++(i++))+i
So the value will be 5+7+7 i.e. 19.


for those who are thinking that what happens when we evaluate the expression from right to left ++i(+(++i(+(++i), like this.
Answer:- Normally in c we read from left to right, and then proceed evaluating the expression on the basis of the associativity of the operator. Likewise, I have done there.
so evaluating the expression in the way ++i(+(++i(+(++i) is wrong.


The correct answer is 18.
==> 5+6+7=18
pre-increament operator has more preference so, for the first “i” value becomes 5 and then it becomes 6 and then 7.
so at last the final answer becomes 18 by adding up all the values.


answer is 18 not 19
it follows operator precedence ,so pre increment has more priority


did u run it in c compiler??


i = 4;
ans = ++i + ++i ;

answer would have been 12 .

as , first i is incremented to 5 , but we don’t print it yet … then it is incremented to 6 .

and now we use the current value of i in hand , thus 6+6=12

now when we have

int i = 4, ans;

ans = ++i + ++i + ++i;

Now + is a binary operator which is left to right associative ;

in addition to the 12 that we got above i will be again incremented to 7 and the value of i is written , thus 12+7=19.

Having said that , it is an undefined behavior of C , and we cannot guarantee a particular output.


yaaa i have compiled


++i= 5


The answer is 19. And I have explained the reason too.
Click on the link and see the answer.