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

后端 未结 7 881
醉酒成梦
醉酒成梦 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:28

    The result of the C++ version will not always be as you write as you are invoking undefined behaviour. In C++ you will get undefined behaviour if you use the value of a variable in an expression when that variable is also modified the same expression unless reading that value is part of determining the value to be written, or the expression contains a sequence point between the read and the write.

    In your expression, you are reading the value of index to determine where to assign the result of the right hand side of the =, but the right hand sub-expression also modifies index.

提交回复
热议问题