Increment & Decrement Operators

Increment & Decrement Operators

Published by: Nuru

Published date: 21 Jun 2021

Increment & Decrement Operators Photo

Increment & Decrement Operators

Increment & Decrement Operators are as follows;

  • The increment & decrement operators can be used only with integer variables, not with constants.
  • The operation performed is to add one to or subtract one from the operand.
  • In other words, the statements: ++x; --y; are the equivalent of these statements:

x = x + 1;                  y = y - 1;

  • Note that either unary operator can be placed before its operand (prefix mode) or after its operand (postfix mode).
  • These two modes are not equivalent. They differ in terms of when the increment or decrement is performed:
  • When used in prefix mode, the increment and decrement operators modify their operand before it's used.

x = 10;                       y = ++x;

Here value of x is incremented first i.e. x becomes 11 and the incremented value is assigned to y.

  • So after execution of those statement x and y both have value 11.
  • When used in postfix mode, they modify their operand after it's used.
  • For example: Consider the following statements:

x = 10;                 y = x++;

  • After these statements are executed, x has the value 11, and y has the value 10.
  • The value of x was assigned to y, and then x was incremented.

Increment & Decrement Operators

Some Examples

Some examples of Increment & Decrement Operators are as follows;

#include
int a, b;
main()
{
/* Set a and b both equal to 5 */
a = b = 5;
/* Print them, decrementing each time. */
/* Use prefix mode for b, postfix mode for a */
printf("\n%d %d", a--, --b);
printf("\n%d %d", a--, --b);
printf("\n%d %d", a--, --b);
printf("\n%d %d", a--, --b);
printf("\n%d %d\n", a--, --b);
return 0;

}

 

#include
#include
void main()
{
int y, m=5, x, l=5;
clrscr();
y=++m;                                                /*A prefix operator first adds 1 to the the operand and the result is assigned to variable on left,*/
printf("\n %d",m);

printf("\n %d",y);
x=l++;                                              /*A postfix operator first assigns the value to the variable on left, and then adds 1 to the operand*/
printf("\n %d",l);
printf("\n %d",x);
getch();
}