Increment and Decrement Operators in C Programming



Definition of C Increment and Decrement Operators

C also provides the unary increment operator (++), and the unary decrement operator (- -). If a variable b is to be incremented by 1, the increment operator (++) can be used rather than the expressions b = b + 1 or b += 1.

If increment or decrement operators are placed before a variable (prefixed), they’re referred to as the pre increment or pre decrement operators, respectively.

If increment or decrement operators are placed after a variable (postfixed), they’re referred to as the post increment or post decrement operators, respectively.

The following table list the increment and decrement operators:

Operator Sample expression Explanation
++ ++a Increment a by 1, then use the new value of a in the expression in which a resides.
++ a++ Use the current value of a in the expression in which a resides, then increment a by 1.
-- --b Decrement b by 1, then use the new value of b in the expression in which b resides.
-- b-- Use the current value of b in the expression in which b resides, then decrement b by 1.

The c program below demonstrates the difference between the pre incrementing and the post incrementing versions of the (++) operator.

Post incrementing the variable b causes it to be incremented after it’s used in the printf statement. Pre incrementing the variable b causes it to be incremented before it’s used in the printf statement.


   #include <stdio.h>
    // function main begins program execution
   int main( void )    {
   int b; 
   b = 10;
      
   printf( "%d\n", b ); // print 10 
   printf( "%d\n", b++ ); // print 10 then postincrement
   printf( "%d\n\n", b ); // print 11                               
   
   printf( "--------------\n" );
   
   b = 10; 
   printf( "%d\n", b );  print 10
   printf( "%d\n", ++b ); preincrement then print 11
   printf( "%d\n", b );  print 11
   return 0 ;                                   
    }  // end function main

    Output:
    10
    10
    11
 ----------
    10
    11
    11


Ads Right