+1

What is the output of i=++i + ++i in C , provided the initial value of i is 2?

9/13/2019 4:05:33 PM

SWETA X

8 Answers

New Answer

+4

AndreaC The Standard says so, the compiler gives you a warning. The expression has two subexpressions. The result of each needs to be calculated first before final adding. What if compiler choose to make a separate copies of i? then each will increment separately and the result could be 6. Since there is a '+' in between, it needs a temporary for storing the results of two additions. Say after incrementing lhs or rhs, the compiler copies the sub result in temp variable, then temp is 3, i is 3 at that point, now increment i again for the other part, i becomes 4, which if added to temp will make the final result 7. If compiler choose to evaluate in left to right order, the final result could be 8.

+3

The answer is Compiler dependent and undefined by C Standards, the expression suffers from "sequence point" issue which happens when a variable is access and modified more than once in the same expression. In the above 'i' is accessed and modified twice.

+2

Even if the variable is the same? I mean, in an expression like ++i + ++j we don't know if i is incremented before j, but in ++i + ++i the final value shouldn't depend on the order of incrementation.

+1

8 because you pre-increment i twice.

+1

AndreaC can you please elaborate the process?

+1

You start with i=2, after the first pre-increment you have i=3, after the second one i=4, finaly the addition.

+1

I see, I didn't consider the possibility of two different copies of i, thank you 🙂

0

AndreaC 👍🙂