Increment and Decrement Operators


Increment and Decrement Operators


The increment and decrement operators are one of the unary operators which are very useful in C language. They are extensively used in for and while loops. The syntax of the operators is given below

1. ++ operand 
2. operand ++ 
3. – – operand
4. operand – – 

            The increment operator ++ adds the value 1 to the current value of operand and the decrement operator – – subtracts the value 1 from the current value of operand. 
++operand and operand++ mean the same when they form statements independently, But they behave differently when they are used in expression on the right hand side of an assignment statement. 

Eg 1:-
For(i=0;i<4;i++)                     for(i=0;i<4;++i)
  printf(“ %d”, i);                      printf(“ %d”, i);
            Output:- 0 1 2 3                      Output:- 0 1 2 3
Here increment operator is used independently, so i++ or ++i gives the same output.
Eg 2:-
m = 5; 
y = ++m; (prefix) 
In this case the value of y and m would be 6 

Suppose if we rewrite the above statement as 

            m = 5; 
            y = m++; (post fix) 

            Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand. The same rules will be applied to operand– – and – –operand.

No comments:

Post a Comment