Question

I have the same code on visual studio C++ and C# and each compiler has a different output although both have the same precedence and associativity table

On C++

    int i = 10;  
    int a = i++ + ++i + i--;  
    printf("a=%u\n",a);

    i = 10;
    a = i++ + i;
    printf("a=%u\n",a);

    int x=2,y=3;
    int z=((x++)*(x++))+((++y)*(++y));
    printf("x=%u , y=%u , z=%u \n",x,y,z);

the output is

a=33
a=20
x=4 , y=5 , z=29

On C#

            int i = 10;
            int a = i++ + ++i + i--;

            Console.WriteLine("a={0}",a);

            i = 10;
            a = i++ + i;

            Console.WriteLine("a={0}", a);

            int x = 2, y = 3;
            int z=((x++)*(x++))+((++y)*(++y));
            Console.WriteLine("x={0} , y={1} , z={2}",x,y,z);

the output is

a=34
a=21
x=4 , y=5 , z=26

In C# I found that the operation obey the precedence table that post-increment has a higher precedence that pre-increment and so it places the value then increment I can't find any logical explanation for this . Could anyone explain this ?

Was it helpful?

Solution 2

In C++ the code has undefined behaviour because side effect of the post-increment operator is not exactly sequenced relative to other operations.

In C# there is such notion as DAS (define assignment state); DAs before Expression i must be equal to DAS after Expression i - 1.

The order of calculation of expression x++ or x-- the following.

  1. Value of x is calculated and saved.
  2. The value is used to calculate x++ or x-- and also saved.
  3. This saved result becomes the result of the operation.

So consider statement

int a = i++ + ++i + i--;

The first expression is i++. i is evaluated. Its value is 10. It is saved as the value of the expression. Then operation ++ is applied. The result of operation is 11. So the output DAS of i is equal to 11. It is the input DAS for the next expression ++i. Here ++i is evaluated because there is pre-increment operator. The value is 12 and the output DAS of i is 12. The order of evaluation of i-- the same as i++. So we have

10 + 12 + 12 = 34

and the output DAS of i of the expression is 11.

Maybe it is not very clear but the difference between C++ and C# is that C# made the process of evaluation of expressions more deterministic and clear, to avoid undefined behaviour.

OTHER TIPS

It's not a case of precedence, but of operand evaluation order and sequencing of side-effects. In C++, evaluation order is unspecified, and you also get undefined behaviour from unsequenced modifications of a variable.

I've no idea whether or not C# specifies the behaviour of such insane code, but you shouldn't write such nonsense in any language.

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