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

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

    In the case of C++, at least, you're invoking undefined behavior by preincrementing and using index without a sequence point in between. If you feed that code to GCC with warnings enabled it will say:

    preinc.cpp:6: warning: operation on ‘index’ may be undefined
    

    I'm guessing that it's undefined as well in C#, but I don't know the language. For C and C++ at the very least though, the answer is that the compiler can do anything it wants without being wrong because your code is erroneous. There's no obligation for different compilers (or even the same compiler) to produce consistent results, either.

提交回复
热议问题