I don't think that the following:
i += 1
or
i = i + 1
is the same as ++i. Or am I wrong? Is there any way to do pre increment without using ++ operator?
I don't think that the following:
i += 1
or
i = i + 1
is the same as ++i. Or am I wrong? Is there any way to do pre increment without using ++ operator?
They are the same. Unless for very simple expressions (like a loop condition), it is better to avoid the ++
or --
operators.
I can't add comments so posting related stackoverflow question here:
How do the post increment (i++) and pre increment (++i) operators work in Java?
As Jeremy already commented, i+=1; and i=i+1; are equivalent to ++i or i++ if they standalone lines of code. To achieve pre/post increment you will have to do the increment before/after the line where you want to use the variable as per the case.
eg- for post increment of a variable named i:
//use value of i here
i += 1;
for pre increment:
i += 1;
//use value of i here
In case of a loop, post increment is pretty straight forward:
for(var i=someValue; i<maxValue; i+=1){
//code here
}
For pre increment:
var i = someValue + 1;
for(; i<maxValue; i+=1){
//code here
}