Is there a difference in ++i
and i++
in a for
loop? Is it simply a syntax thing?
相关问题
- Why isn't mySet.erase(it++) undefined behavior
- Operator Precedence.. () and ++
- Operator Precedence.. () and ++
- Bash Post Increment
- Pre increment and post increment
相关文章
- C/C++ post-increment/-decrement and function call
- i++ vs. ++i in a JavaScript for loop
- Is the behavior of return x++; defined?
- What are the historical reasons C languages have p
- Difference between *ptr += 1 and *ptr++ in C
- Post Increment with respect to Sequence Points
- Why doesn't changing the pre to the post incre
- Post increment operator not incrementing in for lo
It boggles my mind why so may people write the increment expression in for-loop as i++.
In a for-loop, when the 3rd component is a simple increment statement, as in
or
there is no difference in the resulting executions.
For
i
's of user-defined types, these operators could (but should not) have meaningfully different sematics in the context of a loop index, and this could (but should not) affect the behavior of the loop described.Also, in
c++
it is generally safest to use the pre-increment form (++i
) because it is more easily optimized. (Scott Langham beat me to this tidbit. Curse you, Scott)They both increment the number.
++i
is equivalent toi = i + 1
.i++
and++i
are very similar but not exactly the same. Both increment the number, but++i
increments the number before the current expression is evaluated, whereasi++
increments the number after the expression is evaluated.Check this link.
I dont know for the other languages but in Java ++i is a prefix increment which means: increase i by 1 and then use the new value of i in the expression in which i resides, and i++ is a postfix increment which means the following: use the current value of i in the expression and then increase it by 1. Example:
} and the output is:
a++ is known as postfix.
add 1 to a, returns the old value.
++a is known as prefix.
add 1 to a, returns the new value.
C#:
Output:
foreach
andwhile
loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:If the value as evaluated is used then the type of increment becomes significant:
Here is a Java-Sample and the Byte-Code, post- and preIncrement show no difference in Bytecode:
And now for the byte-code (javap -private -c PreOrPostIncrement):