Search Placementyogi.com
 

Increment and Decrement Operators in C

Increment (++) and decrement (--) are very powerful and compact operators in C. Both are unary operator so have only one operand. Increment operator increment operand value by 1 and decrement operator decrement value by one.

Lets discuss each in detail.

Increment ( ++ ) operator in C 

Increment operator (++) increments the value by 1.  

For example 

a++ or ++a  // this is equivalent to a = a + 1

Based on position of operator, it is classified into two type.

  1. Post increment (a++) 
  2. Pre increment (++a)

If both increments the operand value by 1 then whats the difference between them? we will discuss the difference after decrement operator because same concept applies to pre and post decrement operator too.

Decrement ( -- ) operator in C 

Decrement operator (--) decrements the value by 1.  

For example 

a-- or --a  // this is equivalent to a = a - 1

Based on position of operator, it is classified into two type.

  1. Post decrement (a--) 
  2. Pre decrement (--a)

Difference between pre and post, increment decrement operators

Post, as the name indicates , post increment or decrement means, increment or decrement after (post) the operand value is used. 

Lets understand it with an example

#include<stdio.h>
int main()
{
   int i=1,j=1,k=0,l=0;
   k=i++;     /* k=i, i=i+1 First copy i to k then increment i */
   l=j--;     /* l=j, l=l-1   First copy j to l then decrement j */
   printf("i=%d j=%d k=%d l=%d",i,j,k,l);
}

output
--------------------
i=2  j=0  k=1  l=1

In above program you can see the values of k and l are still 1 but i is incremented by 1 and j is decremented by 1.  In k=i++, first values of i is used and then it is incremented because ++ operator is after i, .i.e post increment. same in case of l=j-- .

In case of Preincrement or decrement, operand value is first incremented or decremented then is is used.

#include<stdio.h>
int main()
{
   int i=1,j=1,k=0,l=0;
   k=++i;     /* i=i+1, k=i, First increment i  then copy i to k*/
   l=--j;     /* l=l-1,l=j   First decrement j then copy j to l */
   printf("i=%d j=%d k=%d l=%d",i,j,k,l);
}

Output
--------------------
i=2  j=0  k=2  l=0

In above program ++ and -- is used as pre increment and decrement operator so in statement k=++i; first i values is incremented by 1 and then it is copied to k. Same in l=--j;    

Banner to LogicGuns.com

Hide Page Information
Increment Decrement Operators in c