Interview Question
And so should the interviewer who asks this sort of question. I have been coding for 15 years, and I am quite good with algorithms and most aspects coding in general, and I have no idea what that code would yield, and I want to make a point of never ever finding out either.
Its 12 as Raquibur said it above.
Since its ++i, its preincrement operator which makes i = 3 at first.
So when it goes to compute second ++i, i is already = 3 and preincrement will make it 4.
Next time the value is 5.
So (++i) + (++i) + (++i) = 3 + 4 + 5 = 12.
The explanation for 13 is as follows, the first (++i) evaluates it to 3. But there is no temporary variable created for the expression evaluation. Now the next after the next (++i) is evaluated then the value of i becomes 4. Now because there was no temp variable created, the expression evaluates to (++i)+(++i) = 4 + 4. But after this there is a temp variable with value 8 created and is not effected by further increments of i. Therefore, (++i)+(++i)+(++i) = 4 + 4 + 5 = 13
I dont think the behavior will be undefined here. Pre-increments are always calculated before calculating an expression so before 'j' is calculated, 'i' will be incremented 3 times which gives i = 5 and j = 5 + 5 + 5 = 15.
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression."
The code violates this rule, hence undefined behavior.
The result turns out to be 13 (when run, might be implementation dependent).
The explanation is like this.
++i will increment the value to 3. But its reference will be used
++i will increment the value to 4. Again the reference will be used. Since there is no paranthesis, the compiler will first sum the first two, and evaluate the third one.
4+4+5 = 13
if you had paranthesis
like
j=(++i)+((++i)+(++i)) the result wil lbe 15 for similar resons.
Turbo see first pre-increments i and then use the incremented value in place of i and evaluates the expression i.e,-5+5+5=15.
gcc compiler first increments only 2 instances of pre-increment and uses it.the next pre incremented operand is incremented and added and so on.i,e,=>4+4+5=13
example=>(++i)+(++i)+(++i)+(++i)+(++i),i=2.the expression is evaluated as=>4+4+5+6+7=26.
15
- monu July 27, 2011