In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
In C, what is the difference between using ++i and i++ , and which
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
++iwill increment the value ofi, and then return the incremented value.i++will increment the value ofi, but return the original value thatiheld before being incremented.For a
forloop, either works.++iseems more common, perhaps because that is what is used in K&R.In any case, follow the guideline ‘prefer
++ioveri++‘ and you won’t go wrong.There’s a couple of comments regarding the efficiency of
++iandi++. 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: Is there a performance difference between i++ and ++i in C?
As @OnFreund 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.