Increment and Decrement Operators

The C language's unique “increment” (++) and “decrement” (– –) operators, listed in Table 6.4, are very useful. They increase or decrease an expression by a value of 1.

Table 6.4 Increment and Decrement Operators

Operator Operation

++ Increment expression by 1
–– Decrement expression by 1

Thus, the two statements

val = val + 1;

val++;

are equivalent and so are these statements:

val = val - 1;

val--;

Summary: You can use the ++ and – – operators before or after an expression.

The ++ and – – operators can precede or follow an expression. Placed before an expression, the operator changes the expression before the expression's value is used. In this case, the operator is said to be a “prefix” operator. Placed after an expression, the operator (known as a “postfix” operator) changes the value of the expression after the expression's value is used.

In the DECRMENT.C program, shown below, the decrement operator is used both as a prefix operator and a postfix operator.

/* DECRMENT.C: Demonstrate prefix and postfix operators. */

#include <stdio.h>

main()

{

int val, sample = 3, proton = 3;

val = sample--;

printf( "val = %d sample = %d\n", val, sample );

val = --proton;

printf( "val = %d proton = %d\n", val, proton );

}

Here is the output from DECRMENT.C:

val = 3 sample = 2

val = 2 proton = 2

In the first use of the decrement operator, the statement

val = sample--;

assigns the value of sample (3) to the variable val and then decrements sample to the value 2. Contrast this with the statement

val = --proton;

which first decrements proton to the value 2 and then assigns that value
to val.