Pre Increments and Post Increments in C
Essay by nmohame • June 11, 2019 • Course Note • 666 Words (3 Pages) • 884 Views
Pre Increments and Post Increments
Istiaq Mohammad
The basic concept of using the ++ or -- operator in C is to either increase or decrease the value of a variable by 1.
In the case of using them independently, they are functionally identical.
For example:
x = 3;
x++; //x becomes 4
and
x = 3
++x; //x becomes 4
both yield exactly the same result: x becomes 4.
The main difference between the two is seen when the variable in question is used again, in the same line. In such cases, using x++ retains the original value of x, while using ++x uses the updated value of x.
For example:
int x,y;
x = 3;
y = ++x; // y becomes 4, x becomes 4
y = x++; // y becomes 3, x becomes 4
Another example:
char x = 'A';
printf("%c\n", x++); //Prints A
printf("%c\n", x); // Prints B
x = 'A';
printf("%c\n", ++x); //Prints B
printf("%c\n", x); // Prints B
This is the simplest case.
Things start to get complicated when there are multiple increments in the same line, in which case the order of execution is determined by the precedence of the other operators involved, and then done right to left.
If faced with such a problem, work slowly, step by step, and keep track of the value of each variable in each step.
The increment/decrement operators have higher precedence than the standard operators (+,-,*,/,%).
x = 5;
y = x + ++x;
The value of y will be 12 because x will be incremented first. Switching x and ++x will yield the same result.
Contrary to popular belief, there is no difference in the results between using postfix or prefix increments when used inside a for() loop.
for(i=0;i<5;i++) printf(“%d\n”,i);
and
for(i=0;i<5;++i) printf(“%d\n”,i);
have the same result.
It does however, make a difference when used in a while() loop.
i = 5;
while(i--) printf("%d\n",i);
This will print 4,3,2,1,0 and then exit the loop, and the final value of i will be -1.
i = 5;
while(--i) printf("%d\n",i);
This will print 4,3,2,1 and then exit the loop, and the final value of i will be 0.
It will also work similarly if used in an if() statement.
int x;
x = 1;
if(x--) printf("One\n");
else printf("Zero\n");
x = 1;
if(--x) printf("One\n");
else printf("Zero\n");
This will print One, then Zero. In the first case, x is decreased to zero, but the if() condition retains the original value of 1 and executes. In the second case, x is decreased to zero, and the else condition is executed.
...
...