+ 1

++ Operator

int i=0,x; x= ++i + ++i; Why x is 4?

17th Feb 2017, 1:13 AM
hannes lauckner
hannes lauckner - avatar
4 Réponses
+ 3
++i adds 1 before calculating. ++i = 1 remember that i is always the same variable! since i no longer is 0, the second ++i = 1+1 = 2. you might think it now looks like this: 1 + 2 but that is wrong. it is 2+2. the SAME variable. you just changed it twice. now its 4. I think this is how it works :).
17th Feb 2017, 2:12 AM
Coinage
Coinage - avatar
+ 3
The answer is 4 in C++ but 3 in JavaScript. In C++, both ++ are executed first. So, 'i' becomes 2 and 2+2 becomes 4. In JavaScript, left to right evaluation is done. So, the result is 1+2 which is 3.
17th Feb 2017, 2:17 PM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
0
X equals to 2 not 4. Prefix(++x) proceeds to increment first and then with the expression. Postfix(x++) first evaluates and then the expression.
17th Feb 2017, 1:40 AM
Antonio
Antonio - avatar
0
i tested it and got 4 #include<iostream> using namespace std; int main() { int i=0,x; x = ++i + ++i; cout<<x; return 0; }
17th Feb 2017, 1:47 AM
hannes lauckner
hannes lauckner - avatar