4

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++;

4
  • 3
    In C++, it is undefined behaviour. Commented Oct 2, 2017 at 11:12
  • 3
    You can't really compare two very different languages with very different semantics like this. At least not without understanding the semantics in both languages very well, which would mean you would not actually need to ask this question. Commented Oct 2, 2017 at 11:14
  • @rsp It is before C++17 :P Commented Oct 2, 2017 at 11:16
  • 2
    Executed right to left in cpp. Commented Oct 2, 2017 at 11:21

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's what I was asking for :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.