Computer instructions have the provision of directly adding or subtracting unity to a variable. So, if we use this facility, the operation is quicker than the operation for the statement A = A+ 1; . Therefore, for increasing and decreasing the values of integral objects by unity, it is better to make use of increment operator (++) and decrement operator (- -) , respectively. Another provision with these operators is that the operators may be placed before or after the identifier of the variable. When the operators + + and — are placed before the variable name, these are called pre-increment and pre-decrement operators, respectively. For instance,
Int A= 10, B = 5;
++A* ++B; // This is equivalent to(10+ 1) * (5+ 1) and A= 11,B=6.
When the operators are placed after the names they are called post-increment and post-decrement operators. In this case, the increment is carried out after the current use. For example,
A++* B++; // This is equivalent to 10 x 5 and A = 11 and B = 6.
In case of pre-increment/pre-decrement operators the present value of the variable is first increased/ decreased by unity and then this changed value is used in the application. On the other hand, in case of post-increment/post-decrement operators, the present value of the variable is used in the application and then its value is incremented/ decremented. Table provides a list of all possible increment and decrement operators along with their applications.
Illustrates application of increment and decrement operators.
#include <stdio.h>
void main()
{
int x = 3, y = 5,z = 10,p= 8, A,B,C,D;
clrscr();
A= ++x*++y; // ++has higher precedence level than *
printf("A = %d\t x = %d\t y = %d\n", A, x, y);
B = y--* y-- ;
printf("B = %d \t y = %d \n", B, y);
C = ++z*--z ; //++ and -- have higher precedence level than*
printf("C = %d\t z = %d\n", C, z );
D = p-- * --p; //--p has higher precedence level than *
printf("D= %d\t p= %d\n", D, p);
}
For the first line of the output both x and y are incremented before the multiplication, so, in the result, A is equal to 24, x = 4, y = 6. For the next line of the output, the value y is now 6, so, B = 36; decrement (twice) is done after the multiplication. For the third line of output, Z is first incremented and then decremented before the multiplication because++ and — have higher precedence level than *. So, the result is C = 100 and Z = 10. For the fourth line of the output, the decrement operation –p is carried out before the multiplication. The value of p is again decremented by 1 after the multiplication because of p–. So, D = 49 and p = 6.