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

29th Jan 2017, 9:12 PM
Samir Tabib
Samir Tabib - avatar
4 Réponses
+ 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++;
30th Jan 2017, 5:47 AM
visph
visph - avatar
+ 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
29th Jan 2017, 9:16 PM
Kostas Kolivas
Kostas Kolivas - avatar
+ 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.
29th Jan 2017, 9:21 PM
Samir Tabib
Samir Tabib - avatar
0
@Samir I see what you mean. It's probably the way JS handles increments. Don't really know anything more specific unfortunately
29th Jan 2017, 9:28 PM
Kostas Kolivas
Kostas Kolivas - avatar