Increment and Decrement Operators in C

Increment and decremented operators are used in some programming languages like C, C++, C#, Java, etc. Let’s see how these operators are used in C.

Increment operator (++) increases the value by one and decremented operator (−−) decreases it by one. There are two different ways these operators are used: prefix and postfix.

Prefix

Prefix increment operator increases the value of the variable before returning the output. As shown in the code below, a increases by one.

INPUT
#include <stdio.h>
int main() {
    int a = 5;
    ++a;
    printf("a=%d \n", a);
    return 0;
}
OUTPUT

Increment operator in C

If you assign a new variable b to the output, it will still give the same output. So, the prefix operator increases the value and then assigns it to the new variable.

int a, b;
a = 5;
b = ++a;
printf("b = %d\n", b);
printf("a = %d", a);
OUTPUT

Increment operator in C

Postfix

Post-fix increment operator returns the already assigned value to the variable and then increments the variable. It still gives the same output if you print a.

INPUT
int a = 5;
a++;
printf("a=%d \n", a);
 OUTPUT

Increment operator in C

The difference can be seen only when you assign a new variable to the output. As shown in the code below, the value of b remains the same, because the post-fix operator assigns the value to it then increments the value.

INPUT
int a, b;
a = 5;
b = a++;
printf("b = %d\n", b);
printf("a = %d", a);
 OUTPUT

Increment operator in C

Similarly, the decremented prefix operator decreases the value, then assigns the value to the variable.

INPUT
int a, b;
a = 5;
b = --a;
printf("b = %d\n", b);
printf("a = %d", a);
OUTPUT

Decrement operator in C

Using Floating-point variable instead of integer variable gives similar output as shown in the code below. But if you use both integer and floating point numbers, it can cause error as described in the discussion here.

INPUT
#include <stdio.h>
int main()
{
    float a = 5.1;
    a++;
    printf("a = %f\n", a);
    return 0;
}
 OUTPUT

Increment operator in C

What you cannot do with prefix and postfix operators
  • It’s very handy if you only want to increase the variable by 1 unit. Instead of i += 1 or i=i+1 you can use i++. But these operators only increase or decrease the value by 1 unit, so for higher values, you have to use notations like a = a + 5 or a += 5.
  • You cannot use Increment and decrement operators in Python.
  • You cannot use both operators at once, it results in an error as shown in the code below.
INPUT
int a, b;
a = 5;
b = ++a--;
printf("b = %d\n", b);
 OUTPUT

Increment operator in C

  • If you increment a constant, say 5++ the compiler will show a similar lvalue error. So a constant cannot be directly incremented or decremented.
INPUT
int a=5;
5++;
printf("a = %d\n", a);
return 0;
 OUTPUT

Increment operator in C

0
0

Related Posts