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



In C, ++ and -- operators are called increment and decrement operators. They are unary operators needing only one operand. Hence ++ as well as -- operator can appear before or after the operand with same effect. 

That means both i++ and ++i will be equivalent.

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

and 

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

both will make i=6.

However, when increment expression is used along with assignment operator, then operator precedence will come into picture. 

i=5;
j=i++;

In this case, precedence of = is higher than postfix ++. So, value of i is assigned to i before incrementing i. Here j becomes 5 and i becomes 6.

i=5;
j=++i;

In this case, precedence of prefix ++ is more than = operator. So i will increment first and the incremented value is assigned to j Here i and j both become 6.

#include <stdio.h>
int main() {
   int i=5,j;
   j=i++;
   printf ("
after postfix increment i=%d j=%d", i,j);    i=5;    j=++i;    printf ("
after prefix increment i=%d j=%d",i,j);    return 0; }

The output is

after postfix increment i=6 j=5
 after prefix increment i=6 j=6

Advertisements