Increment and Decrement Operators


C allows two very efficient operators that are not usually found in other programming languages. These are the increment and decrement operators:

++ and --

The ++ operator adds 1 to the operand, while -- subtracts 1. Both are unary operators and takes the following form :

++a or a++;
--a or a--;

We use increment and decrement operators in for and while loops.

While ++a and a++ mean the same thing when they form statements independently, they behave differently when they are used in expressions on the right-hand side of an assignment statement.


Example of ++ operator

Program
#include <stdio.h>

int main() {
  int i=0;
  printf("Preincrement => \n");
  while(i<=10)
  {
   printf("i = %d\n",i);
   ++i;
  }
  i=0;
  printf("Postincrement => \n");
  while(i<=10)
  {
   printf("i = %d\n",i);
   i++;
  }
  return 0;
}

Example of -- operator

Program
#include <stdio.h>

int main() {
  int i=10;
  printf("Predecrement => \n");
  while(i>=0)
  {
   printf("i = %d\n",i);
   --i;
  }
  i=10;
  printf("Postdecrement => \n");
  while(i>=0)
  {
   printf("i = %d\n",i);
   i--;
  }
  return 0;
}