find output

int main()
int i=1,j;
j= i+ ++i;
this program should output 3… then why it is giving 4 as output plz help…

@shashank13_ , addition occurs from left to right. That was explained in this link I gave in my answer. The position of ++i does not matter. Due to ++ having a Higher Precedence, the ++i is calculated first, and then the addition.

Oh, nearly forgot about your original question.

You are getting your output because, first the ++i is calculated, which changes i to 2. Then, the addition takes place, thus getting 2 + 2. And, the result of 2 + 2 is ________________ Sorry, I’ll leave you to find that out ( unless you’re that bad at math, you should be able to find that ). And, lastly, the assignment takes place and j gets the value _________ ( still not gonna reveal that ).

But, this is just what I predict. It’s impossible to guarantee that others will get the same because of the Undefined Behavior Part.

1 Like

Okay let me explain why this happened

First see this image and make your concepts clear about operators precedence

alt text

As you can see “++” operator has higher precedence than “+” operator so,

Now let me tell you the step by step execution of your code

In main():
    j= i + ++i;
    ...... as ++ has higher precedence than + so breaking above expression in parts
        First ++i will get executed
        so (++i) means ++1 that is i becomes 2
    As i = 2
    so j=4
    and print j will print 4.

Hope you understood the concept…


1 Like

plz… some one answer iam a beginner and is confused with this problem

Read my naswer on your previous question.

thks… but pls tell if addition occurs left to right or right to left.? which means whether the value first enter in i(left to right) or in ++i(right to left)

thanks @arun_as for clearing the doubt…

thanks @rishabhprsd7

welcome @shashank13_ … :slight_smile: