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.
Okay let me explain why this happened
First see this image and make your concepts clear about operators precedence
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(): i=1 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 Now, As i = 2 j=2+2 so j=4 and print j will print 4.
Hope you understood the concept...
plz… some one answer iam a beginner and is confused with this problem
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)
welcome @shashank13_ …