+ 1

var x=0; for(;x<=8;x++){ x+=x - x++; } alert(x+1); //output= 10 //do u have any explanation?

17th Jun 2017, 12:41 PM
islam moheb
islam moheb - avatar
7 Answers
+ 2
OK, so in the loop you first add x to x, leaving you with 2x, then you subtract x, which leaves you with x. After that, x is incremented by one (the post fix ++ is executed afterwards). Meaning every loop increments x by one. Your stop condition is x<=8. This means the last loop execution is with x=8. Because the loop body increments x by one, x has a value of 9 after the loop was executed. The last statement is to print x+1, resulting in print(9 + 1).
17th Jun 2017, 1:15 PM
Iqon
0
What code are you using?
17th Jun 2017, 12:58 PM
NulledNVoided
NulledNVoided - avatar
0
js
17th Jun 2017, 1:01 PM
islam moheb
islam moheb - avatar
0
Put a print line in the for loop, maybe you cN figure it out. BTW it is not recommended to change the variable both on the left and right side of your assignment. A lot languages do not specify the correct behavior in this case, so it is up to the js engine you use what the result is.
17th Jun 2017, 1:05 PM
Iqon
0
I think that because you add x like 3 or 4 times then restarts again to get 10
17th Jun 2017, 1:06 PM
NulledNVoided
NulledNVoided - avatar
0
this code is right and it's output is 10... I'm asking for explanation...
17th Jun 2017, 1:08 PM
islam moheb
islam moheb - avatar
0
The main reason why code like this is considered a code smell, is because the language specification normally states that the post increment operator is applied after the variable is accessed. The problem in this statement is, that x is accessed 3 times. It is up to the specific implementation at which point the operator is applied. 1. After adding the first two x 2. After adding the second two 3. Before assigning 4. After assigning Each of this possibilities could change the outcome of your code snippet
17th Jun 2017, 2:47 PM
Iqon