0
What's the equivalent of the following code in JavaScript ?
#include <iostream> using namespace std; int main() { int i=0,j=i; i +=++i+i++-++j; cout<<i; return 0; }
4 Antworten
+ 3
Shorthand writting is often hardly readable...
The diffference between handling the same expression in C++ and JS seems to come from their respectivly assignement handling ( and so, the '+=' is important ):
i += ++i + i++ - ++j
In C++, computed as ++i pre-increment of i, so i==1 now ( and the '+=' is important because i no more equals zero ^^ ), but not in JS ( in this case, appears to compute without updating value of i during calcul ).
With the second ( post ) incrementation of i, i is modified after use of is value of 1 ( still 0 in JS )
And the third ( pre ) incrementation of j ( initialized to value of i == zero ) substract -1 in all case...
So, in C++: i += 1 + 1 - 1, but during the calcul, i value change twice, once during calcul, once after: i = i + 1 + 1 - 1 <=> i = 1 + 1 + 1 - 1 == 3++ == 4
While in JS: i += 1 + 0 - 1, but i value don't be modified before affectation: i = i + 1 + 0 - 1 <=> i = 0 + 1 + 0 - 1 == 0++ == 1
Well: to obtain the same result in JS, you must decompose your inlined calcul:
var i = 0;
var j = i;
++i;
i += i;
i += i - ++j;
i++;
+ 1
var i = 0;
var j = i;
i += ++i + i++ - ++j; // += is not really required here since i = 0
console.log(i);
Javascript uses mainly C/C++ syntax. It's not all that different
+ 1
@Kostas : thanks, I know both languages syntaxes. my question is about post and pre incrementation. In fact,your code prints 1 . my c++ code prints 4.
0
@Samir
I see what you mean. It's probably the way JS handles increments. Don't really know anything more specific unfortunately