Subscribe Us

Increment and Decrement operators in C -smartduniya

Increment and Decrement operator in c

Introducing to C increment and decrement operators

C provides two operators for incrementing and decrementing the value of variables.

  • The increment operator ++ add 1 to its operand.
  • The decrement operator - - subtracts 1 from its operand

The C increment and decrement operators cann be used either as prefix operator or postfix operators as follow

 

The C increment operator in both prefix or postfix contexts is to add 1 to a variable.  But the expression ++variable increments variable before its value is used, whereas variable++ increments variable after its value has been used.

Example of C Increment Operator

Let's take a look at a simple example to demonstrate prefix and postfix of C increment operator.

#include <stdio.h>
void main() {
int x = 10;
int y;

/* prefix */
y = ++x;
printf("x = %d\n",x);
printf("y = %d\n",y);
x = 10;
/* postfix */
y = x++;
printf("x = %d\n",x);
printf("y = %d\n",y);
return 0;
}

 

write the code on your c compiler and run the code you will get the below result

x = 11
y = 11
x = 11
y = 10

 

Note that in both cases x is 11 however y is 11 in the first case and 19 in the second case.

So in the case that the variable value is not used, there is no difference between prefix or postfix of the increment operator.

Post a Comment

0 Comments