Difference Between I++ and ++I

What is the difference between ++i and i++?

  • ++i will 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 i held before being incremented.

     i = 1;
    j = i++;
    (i is 2, j is 1)

For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R.

In any case, follow the guideline "prefer ++i over i++" and you won't go wrong.

There's a couple of comments regarding the efficiency of ++i and 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:
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.

What's the difference between --i and i--?

If, for example, i = 5:

--i decrements i by 1 then gives you the value of i (4).

i-- gives you the value of i (5) then decrements it by 1.

Both will give you the same result in a for loop.

What's the difference between i++ vs i=i+1 in an if statement?

If you use i++, the old value will be used for the calculation and the value of i will be increased by 1 afterwards.

For i = i + 1, the opposite is the case: It will first be incremented and only then the calculation will take place.

If you want to have the behavior of the second case with the brevity of the first, use ++i: In this case, i will first be incremented before calculating.

For more details and a more technical explanation, have a look at the docs for Assignment, Arithmetic, and Unary Operators!

What is the difference between i++ and ++i?

Oddly it looks like the other two answers don't spell it out, and it's definitely worth saying:


i++ means 'tell me the value of i, then increment'

++i means 'increment i, then tell me the value'


They are Pre-increment, post-increment operators. In both cases the variable is incremented, but if you were to take the value of both expressions in exactly the same cases, the result will differ.

what is difference between ++i and i+=1 from any point of view

i = 10
printf("%d", i++);

will print 10, where as

printf("%d", ++i);

will print 11

X = i++ can be thought as this

X = i
i = i + 1

where as X = ++i is

i = i + 1
X = i

so,

printf ("%d", ++i); 

is same as

printf ("%d", i += 1);

but not

printf ("%d", i++);

although value of i after any of these three statements will be the same.



Related Topics



Leave a reply



Submit