Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

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

What is the difference between ++i and i++ in c? please tell in detailed manner with a easy example


1 Answer
Jayashree

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 ("\nafter postfix increment i=%d j=%d", i,j);
i=5;
j=++i;
printf ("\n 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

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.