Regarding pre and post increment. | Sololearn: Learn to code for FREE!

+5

Regarding pre and post increment.

can you please check my code"test" and explain the reason for difference in the output.

c++

12/19/2016 6:42:36 AM

Rishabh Agrawal

2 Answers

New Answer

+5

Yeah, for "i=1; ++i = ++i + i;" : the first prefix increment operator "++i" increments i by 1 BEFORE the expression happens. So now i == 2, but when assigning "++i + i" to i, the second "++i" increases i again by 1 BEFORE the expression happens. Now i = 3, therefore i = 3 + 3 = 6. For "j=1; ++j +=j;" : the "++j" increases j by 1 BEFORE the expression happens, so now j = 2. The expression "j+=j" or "j = j + j" is equivalent to j = 2 + 2 = 4.

+1

thanks for you answer @antek you made it very clear to me.