Index, assignment and increment in one statement behaves differently in C++ and C#. Why?

后端 未结 7 893
醉酒成梦
醉酒成梦 2021-01-18 16:34

Why is this example of code behaving differently in c++ and C#.

[C++ Example]

int arr[2];
int index = 0;
arr[index]         


        
7条回答
  •  星月不相逢
    2021-01-18 17:09

    Note: Acording to @Eric Lippert's answer, the behavior is strictly defined for C#, so let me reword my answer on this.

    This code:

    arr[index] = ++index;
    

    Is hard to read even if the C# compiler knows exactly how to evaluate it and in which order. For this reason alone it should be avoided.

    The MSDN page on C# Operators goes so far as pointing out that this behaviour might be undefined, even though Eric points out it is not. The fact that multiple sources of documentation (I'll trust Eric on this however) gets it different is also a tell that this might be something best left alone.

提交回复
热议问题