What is the difference between ++i and i++?,
In C, what is the difference between using
i++, and which should be used in the incrementation block of a
++iwill increment the value of
i, and then return the incremented value.
i = 1; j = ++i; (i is 2, j is 2)
i++will increment the value of
i, but return the original value that
iheld before being incremented.
i = 1; j = i++; (i is 2, j is 1)
for loop, either works.
++i seems more common, perhaps because that is what is used in
In any case, follow the guideline “prefer
i++” and you won’t go wrong.
There’s a couple of comments regarding the efficiency of
i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.
The efficiency question is interesting… here’s my attempt at an answer:
As notes, it’s different for a C++ object, since
operator++() is a function and the compiler can’t know to optimize away the creation of a temporary object to hold the intermediate value.
That’s the answer What is the difference between ++i and i++?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.
The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you