Index, assignment and increment in one of the operators behave differently in C ++ and C #. What for?

Why does this code example behave differently in C ++ and C # .

[C ++ example]

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

The result will be arr [1] = 1 ;

[C # example]

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

The result of which will be arr [0] = 1 ;

I find it very strange. Of course, there must be some justification for both languages ​​in order to implement it differently? I wonder what to deduce C ++ / CLI ?

+5
source share
7 answers

++ , , - . arr[index] = ++index; undefined.

+4

index ++ ++. : arr[index] = index + 1 . , ++ , arr [0] = 1, arr [1] .

+3

++, , undefined index . GCC , :

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

, undefined, #, . C ++, , , , , , , . ( ) .

+1

: @Eric Lippert answer, #, .

:

arr[index] = ++index;

, # , . .

MSDN # , , undefined, . , ( , , ) , , .

+1

++ , , undefined. ++ undefined, , , , , .

index, , =, - index.

0

index # - , , .

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

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

C ++, however, works with an object reference, so the procedure will look like this:

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

Note: if you applied the operator to an object (for example, you overloaded the ++ operator), then C # will behave like C ++, since the types of objects are passed as links.

-1
source

All Articles