C increment and decrement operators

  • In implementation when we need to increase the value of the variable by 1 then go for increment or decrement operators.
  • When we are working with increment/decrement operators then modification between old and new value will be +/-1.
  • Depends on the position C increment and decrement operators are classified into 2 types: pre and post operators.
  • When symbol is available before the operand the it is called pre operator, if the symbol is there after the operand then it is called post operator.
  • When we are working with the post-operators before evaluating the expression the value need to be change i.e. modification first and substitution later.
  • When we are working with the post-operators after evaluating the expression the value need to be change i.e. substitution first and modification later.

int a,b;
a=1;

Syntax 1(pre increment):b=++a;
Explanation:
First increments the value of a by 1 then evaluate the expression i.e. b=a;
output: a=2 b=2
Syntax 2(post increment): b=a++;
Explanation:
First evaluate the expression i.e. b=a; then increment the value of a by 1
output: a=2 b=1
Syntax 3(pre decrement): b=–a;
Explanation:
First decrements the value of a by 1 then evaluate the expression i.e. b=a;
output: a=0 b=0
Syntax 4(post decrement): b=a–;
Explanation:
First evaluate the expression i.e. b=a;then decrement the value of a by 1
output: a=0 b=1

Operators priority:

1.()
2.+,-,/,++,–
3.*/,%
4.+,-
5. <>,<=,>=
6.==,!=
7.&&
8.||
9.!!
10.==
11. ++,–

Examples:

void main()
{
int a;
a=10;
++a;
printf(“a=%d”,a);
}

Output:11

void main()
{
int a;
a=10;
a++;
printf(“a=%d”,a);
}

Output:11

void main()
{
int a,b;
a=5;b=10;
a=a– + –b;
b=b– + –a;
printf(“a=%d b=%d”,a,b);
}

output: a=12 and b=20

Powered by k2schools