2

I noticed that there are two different behaviors in the assignment of an array value, like arr[i] = ++i.

In C++

int arr[] = {0,0};
int i = 0;
arr[i] = ++i;
cout << arr[0] << ',' << arr[1] << endl;
// the output is 0,1

But in JavaScript

let arr = [0,0]
let i = 0
arr[i] = ++i
console.log(arr)
// the output is [1,0]

Why is there such a difference? I think the behavior of C++ is more natural.

Yucheng Zhou
  • 31
  • 1
  • 3
  • 5
    C++ and Javascript are two ***very*** different languages, which very different semantics when it comes to arrays as well as the behavior of the increment/decrement operators. More specifically, in most specifications of C++ the assignment you have will lead to *undefined behavior*, because you use and modify `i` without any specified sequence order. – Some programmer dude Jul 26 '23 at 08:39
  • 2
    `I think the behavior of C++ is more natural` if you come to javascript from a C++ background then you would think that - but that C++ behaviour surprises me - but then, I'd never write such code in the first place – Jaromanda X Jul 26 '23 at 08:48
  • It appeared only recently in the C++ standard (not fully sure, I think C++20, maybe already C++17) that sequencing for the assignment operator has been introduced. Before, evaluation of left and right sight had been unsequenced (as @Someprogrammerdude mentioned already – with all those consequences). And in those days you might have examined the same behaviour in C++ as well – or anything else, well, it's UB! – Aconcagua Jul 26 '23 at 08:48
  • In some situations in C++ the order in which things happen is unspecified. The exact details are complex and have also changed over the history of C++. The reason for this however is that having an unspecified order allows C++ compilers to generate more efficient code. But this places a burden on the programmer to know the situations where the unspecified order leads to undefined behaviour and to avoid them. I barely know JavaScript but I guess the priorities were different there. More C++ details [here](https://en.cppreference.com/w/cpp/language/eval_order). – john Jul 26 '23 at 08:53

0 Answers0