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

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

    index in C# is a value type, which means you return a new instance of the value when you perform operations on it.

    If you imagine it as a procedure instead of an operator, the procedure would look like this:

    public int Increment(int value)
    {
       int returnValue=value+1;
       return returnValue;
    }
    

    C++, however, works on the reference of the object, so the procedure would look like:

    int Increment(int &value)
    {
       value=value+1;
       return value;
    }
    

    Note: if you had been applying the operator on an object (say overloaded the ++ operator) then C# would behave like C++, since object types are passed as references.

提交回复
热议问题