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

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.

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

 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

 OUTPUT

Increment operator in C

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

INPUT

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

 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

 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

 OUTPUT

Increment operator in C

Related Posts