In C, what is the difference between using ++i
and i++
, and which should be used in the incrementation block of a for
loop?
The following C code fragment illustrates the difference between the pre and post increment and decrement operators:
int i;
int j;
Increment operators:
i = 1;
j = ++i; // i is now 2, j is also 2
j = i++; // i is now 3, j is 2
They both increment the number. ++i
is equivalent to i = 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, whereas i++
increments the number after the expression is evaluated.
Example:
int i = 1;
int x = i++; //x is 1, i is 2
int y = ++i; //y is 3, i is 3
Please don't worry about the "efficiency" (speed, really) of which one is faster. We have compilers these days that take care of these things. Use whichever one makes sense to use, based on which more clearly shows your intent.
a=i++ means a contains current i value a=++i means a contains incremented i value
++i
(Prefix operation): Increments and then assigns the value
(eg): int i = 5
, int b = ++i
In this case, 6 is assigned to b first and then increments to 7 and so on.
i++
(Postfix operation): Assigns and then increments the value
(eg): int i = 5
, int b = i++
In this case, 5 is assigned to b first and then increments to 6 and so on.
Incase of for loop: i++
is mostly used because, normally we use the starting value of i
before incrementing in for loop. But depending on your program logic it may vary.
++i
: is pre-increment the other is post-increment.
i++
: gets the element and then increments it.
++i
: increments i and then returns the element.
Example:
int i = 0;
printf("i: %d\n", i);
printf("i++: %d\n", i++);
printf("++i: %d\n", ++i);
Output:
i: 0
i++: 0
++i: 2