Question

I have a simple code snippets which shows different behavior when build using C++ compiler and C# compiler.

C#

static void Main(string[] args)
{
   int i = 0;
   i += i++;
   Console.WriteLine(i);
   Console.ReadLine();
}

The result of i is 0. Copied from this link. For i = 0, why is (i += i++) equal to 0?

C++

int main() 
{
    int i = 0;
    i += i++;
    cout << i << endl;
}

The result of i is 1.

I just want to know why there is difference in code output in C# and C++.

Was it helpful?

Solution

The designers of C# and C++ and C made different decisions about how to handle order of evaluation whereas in C# the order of evaluation if from left to right:

Operands in an expression are evaluated from left to right.

and side effects take place from left to right as well.

In C++ this is not the case, the draft C++ standard section 1.9 Program execution paragraph 15 says:

Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

and if side effects on the same scalar object is sequenced relative to another side efect the result it undefined behavior:

[...]If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.[...]

and the draft gives examples of undefined behavior:

i = i++ + 1; // the behavior is undefined

which if we look at the expression from your code:

i += i++;

which is equivalent to:

i = i + i++ ;

we can now clearly see it invokes undefined behavior which means the result is unpredictable and can not be relied on.

OTHER TIPS

In C, an expression like i= i++; has an undefined behavior, and can evaluate to 0 or 1 (incrementing after evaluation of the whole expression or before the assignment are both possible).

This was a strange design decision, as apparently innocent and perfectly justified code can produce unexpected results, like sum= a[i++] + a[i++];. Strangely too, nobody seems to be bothered.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top