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
In C# there is no difference when used in a for loop.
outputs the same thing as
As others have pointed out, when used in general i++ and ++i have a subtle yet significant difference:
i++ reads the value of i then increments it.
++i increments the value of i then reads it.
As @Jon B says, there is no difference in a for loop.
But in a
while
ordo...while
loop, you could find some differences if you are making a comparison with the++i
ori++
Yes, there is a difference between
++i
andi++
in afor
loop, though in unusual use cases; when a loop variable with increment/decrement operator is used in the for block or within the loop test expression, or with one of the loop variables. No it is not simply a syntax thing.As
i
in a code means evaluate the expressioni
and the operator does not mean an evaluation but just an operation;++i
means increment value ofi
by 1 and later evaluatei
,i++
means evaluatei
and later increment value ofi
by 1.So, what are obtained from each two expressions differ because what is evaluated differs in each. All same for
--i
andi--
For example;
In unusual use cases, however next example sounds useful or not does not matter, it shows a difference
Yes, there is. The difference is in the return value. The return value of "++i" will be the value after incrementing i. The return of "i++" will be the value before incrementing. This means that code that looks like the following:
Therefore, a would be 2, and b and c would each be 1.
I could rewrite the code like this:
There is no actual difference in both cases '
i
' will be incremented by 1.But there is a difference when you use it in an expression, for example:
One (++i) is preincrement, one (i++) is postincrement. The difference is in what value is immediately returned from the expression.
Edit: Woops, entirely ignored the loop side of things. There's no actual difference in for loops when it's the 'step' portion (for(...; ...; )), but it can come into play in other cases.