C ++ vs C # - array

Let there be an array a = {0,1,2,3,4}and int i = 2. Now we will do several operations in both (always starting from the point above).

a[i] = i++; // a = {0, 1, 2, 3, 4}
a[i] = ++i, // a = {0, 1, 3, 3, 4}

This seems logical to me. But for C ++, I get different results:

a[i] = i++;  // a = {0, 1, 2, 2, 4}
a[i] = ++i;  // a = {0, 1, 2, 3, 4}

I do not understand the results that I get in C ++;

+4
source share
1 answer

C # is evaluated from left to right, so in the first case, you get:

a[2] = 2; // 1)
a[2] = 3; // 2)

In C ++, this behavior is undefined, but since C ++ 17, the assignment operator evaluates from right to left:

a[3] = 2; // 1)
a[3] = 3; // 2)

Different languages, different rules.

+7
source

Source: https://habr.com/ru/post/1686748/


All Articles