Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ vs C# - array

Tags:

c++

c#

Let's have an array a = {0,1,2,3,4} and an int i = 2. Now let's do few 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 don't understand the results I get in C++;

like image 836
Štěpán Chvatík Avatar asked Mar 07 '23 22:03

Štěpán Chvatík


1 Answers

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

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

In C++, that is undefined behavior, but since C++17, an assignment operator is evaluated from right to left:

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

Different languages, different rules.

like image 131
Rakete1111 Avatar answered Mar 17 '23 03:03

Rakete1111