425 views
0 votes
0 votes
How to work on such question ? Answer is : 19

#include <stdio.h>

int main() {
    
    int i = 4, ans;

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

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

    return 0;
}

1 Answer

2 votes
2 votes

Its one of those undefined behaviors of C.

The increment and Decrement operators .. their associativity is from right to left .

So, in general if you want to execute a code like this :

int i=10;
printf("%d,%d,%d,%d",i++,++i,i++,++i);

what post increment does is , it first uses the current value of i and then updates it , but pre increment first increments the value of i and but we get to use it when other things get evaluated . 

so for the above example it will work like this .

first , the rightmost ++i will get executed it will make the value of i = 11 .. but we will still not use it .

Next we have i++ , we print i=11 and then increment it to 12 .

then again we have a pre increment it increments i to 13 , but we don't use it .

then again we have i ++ we print 13 and increment i to 14 .

now 14 is our current value of i , therefore in place of those pre increments , we print 14 .

thus our answer is , 13 , 14 ,11 , 14 .

in your question , if it were .. 

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.

Related questions

2 votes
2 votes
1 answer
2
sushmita asked Apr 15, 2017
755 views
void main() { char *p="cprogramming"; }I know the string literal "cprogramming" is stored in read only data segment. But where will the pointer p be stored, in stack or r...
2 votes
2 votes
1 answer
4
Sandeep Suri asked Aug 1, 2017
4,039 views
#include <stdio.h>int main(){ int x = 3;if (x == 2);x = 0;if (x == 3) x++;else x += 2;printf("x = %d", x);return 0;}