• Home
  • 3.5 Pre-Decrement and Post-Decrement

3.5 Pre-Decrement and Post-Decrement

View Categories

3.5 Pre-Decrement and Post-Decrement

< 1 min read

Table of Contents

The decrement operator can appear before or after a variable. Both forms decrease the variable by 1, but they differ in the value produced when the operation is used inside an expression.

#include <stdio.h>

int main()
{
    int a = 5;
    int b = 5;

    printf("Pre-decrement: %d\n", --a);
    printf("Post-decrement: %d\n", b--);

    printf("a = %d\n", a);
    printf("b = %d\n", b);

    return 0;
}

Example Output #

Pre-decrement: 4
Post-decrement: 5
a = 4
b = 4

Explanation #

In pre-decrement:

--a

a is decremented before its value is used by the expression. Therefore, --a produces 4.

In post-decrement:

b--

the original value of b is used by the expression first. The decrement is then applied, so the expression produces 5, while b becomes 4.

Both forms ultimately decrease the variable by 1; the difference is the value produced by the expression.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *