Pre-Decrement and Post-Decrement in C

Q1. What happens when we use pre-decrement and post-decrement with numeric literals?

Answer:

The use of decrement operator with constants results in error because the decrement operator only works on rvalues (the values to which we can assign some constant values) such as variables and numeric literals are rvalues.

Example:

C




// C program to demonstrate the use of decrement operator
// with literals
#include <stdio.h>
  
int main()
{
  
    int a, b;
  
    a = 10 --;
    b = --10;
  
    printf("a=%d, b=%d", a, b);
  
    return 0;
}


Output

sum.c: In function 'main':
sum.c:7:9: error: lvalue required as decrement
operand
a = 10--;
^~
sum.c:8:7: error: lvalue required as decrement
operand
b = --10;

In the above example, we have applied the decrement operator to literals and we get the error “lvalue required as decrement operand” which means a variable should be used so that decremented value is stored in that variable because “10 = 10 -1” is a wrong statement and we know that “a–” is equivalent to “a = a-1”.

Q2. What is the difference between Pre-Decrement and Post-Decrement in C?

Answer:

There are only two major differences between the pre-decrement and post-decrement operators in C. They are as follows:

  1. Syntax: The pre-decrement is added as prefix to the variable, while the post-decrement is appended as suffix.
  2. Operation: The dercement is immediately performed in case of pre-decrement while in post-decrement, all the other operations are performed first, only then decrement is done.


Pre-Decrement and Post-Decrement in C

Pre-decrement and post-decrement are the two ways of using the decrement operator to decrement the value of a variable by 1. They can be used with numeric data type values such as int, float, double, etc. Pre-decrement and Post-decrement perform similar tasks with minor distinctions.

In this article, we will discuss the pre-decrement and post-decrement operators in C.

Similar Reads

Pre-Decrement in C

In pre-decrement operation, the decrement operator is used as the prefix of the variable. The decrement in value happens as soon as the decrement operator is encountered....

Post-Decrement in C

...

Example of Pre-Decrement and Post-Decrement

In post-decrement operation, the value is decremented after all the other operations are performed i.e. all the other operators are evaluated. The decrement operator is used as the suffix to the variable name....

FAQs on Pre-Decrement and Post-Decrement in C

...