The Decrement Operator - C Operator

C examples for Operator:Increment Decrement Operator

Introduction

The decrement operator works in the same way as the increment operator.

It takes the form -- and subtracts 1 from the variable.

For example, assuming the variables are of type int, the following three statements all have exactly the same effect:

count = count - 1;
count -= 1;
--count;

They each decrement the variable count by 1.

It works similarly to the increment operator in an expression.

For example, suppose count has the value 10 in the following statement:

Demo Code

#include <stdio.h> 
int main(void) { 
  int total = 0;/*w w w .  ja v  a 2 s . c  o m*/
  int count = 10;

  total = --count + 6;
  
  printf("total: %d",total);
  printf("count: %d",count);
  return 0; 
}

Result

The variable total will be assigned the value 15 (from 9 + 6).

The variable count, with the initial value of 10, has 1 subtracted from it before it is used in the expression so that its value will be 9.

For example, suppose count has the value 5 in this statement:

Demo Code

#include <stdio.h> 
int main(void) { 
  int total = 0;//from w  ww .j a  va2s. c  o  m
  int count = 5;

  total = --count + 6;
  
  printf("total: %d",total);
  printf("count: %d",count);
  return 0; 
}

Result

total will be assigned the value 10 (from 4 + 6).

In this statement:

Demo Code

#include <stdio.h> 
int main(void) { 
  int total = 0;/*from  w  ww.  j  a  va 2s .co  m*/
  int count = 5;

  total = 6 + count-- ;
  
  printf("total: %d",total);
  printf("count: %d",count);
  return 0; 
}

Result

total will be assigned the value 11 (from 6 + 5).

Both the increment and decrement operators can only be applied to integer types, including integer types that store character codes.


Related Tutorials