﻿ C - Difference between ++i and i++

# Pre Increment Operators

## C - Difference between ++i and i++:

C offers several shorthand versions of the preceding type of assignment. When the operators precede (i.e., come before) the variable, the operation is called pre-increment and when the operators succeed (i.e., come after) the variable, the operations is called post-increment. Consider the following code snippets:

``````
total = i++;    /* Statement 1 */
and
total = ++i;    /* Statement 2 */``````

The first statement is equivalent to:

``````
total = i;
i = i + 1;``````

while the second statement is equivalent to:

``````
i = i + 1;
total = i;``````

So, the said statements (1) and (2) do not have the same effect. The ++ in i++ is called post increment operator and ++i is called the pre increment operator.

Example: ++i and i++

``````#include <stdio.h>

int main()
{
int total = 100;
int i = 10;
printf("The initial value of total and i is : %d, %d", total, i);
total = ++i;
printf("\nAfter applying ++i value of total and i is : %d, %d", total, i);
total = 100;
i = 10;
printf("\n\nThe initial value of total and i is : %d, %d", total, i);
total = i++;
printf("\nAfter applying i++ value of total and i is : %d, %d", total, i);
return 0;
}
``````

Output:

```The initial value of total and i is : 100, 10
After applying ++i value of total and i is : 11, 11

The initial value of total and i is : 100, 10
After applying i++ value of total and i is : 10, 11
```

++ in for construct:

In the following for construct:

``````for (i =0; i++<5;..)
``````

The value of i is compared 5 and then incremented, after which the loop is entered.
On the other hand, if the construct is modified to:

``````for (i=0; ++ i < 5;..)
``````

The value of i is first incremented and then compared to 5 and then the loop is entered.
So in the first case the body of the loop will be executed 5 times and in the second case it will be executed 4 times only.

Example: i++ in for construct:

``````#include <stdio.h>
int main()
{
printf("i++ in for construct:");
for (int i =0; i++<5;)
{
printf("\nValue of i is %d",i);
}
return 0;
}
``````

Output:

```i++ in for construct:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
Value of i is 5
```

Example: ++i in for construct:

``````#include <stdio.h>
int main()
{
printf("++i in for construct:");
for (int i =0; ++i<5;)
{
printf("\nValue of i is %d",i);
}
return 0;
}
``````

Output:

```++i in for construct:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4

```

﻿

## C Programming: Tips of the Day

How to use __FILE__ macro shows full path?

Try

```#include<string.h>

#define __FILENAME__ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__)
For Windows use '\\' instead of '/'.
```

Ref: https://bit.ly/3mOf045

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook