Microsoft Interview Question
Developer Program Engineersi tried in C#
Console.Write(b++ * ++b);
it gave me 15,
it is assiging value first and then incrementing when i say b++,
where as it is incrememting value first and assigning value when i say ++b
so it becomes 3*5 = 15
C# specifies that the order of evaluation is left-to-right with all side effects taking effect before next subexpression is evaluated. Hence the program is well-defined and indeed gives the answer 15.
C and C++ make no such gurantee
In Java, this also gives 15.
the reason is I think i++ means it uses the value of i (3 at that time) and increments the value (to 4) and then ++i increments the value before using. i (=5) used here.
so i++*++i = 3*5 = 15
Undefined behavior ("Between the previous and next sequence point an object shall have its stored value modified at most once ...").
- Anonymous July 23, 2011But even if that was not the case, the order in which the two sub-expressions, b++ and ++b, are evaluated is unspecified. Finally, when the post increment happens is unspecified as long as it is after the value of b++ has been determined and before the next sequence point.