Increment and decrement operators: ++, --

Home / C Programming / Increment and decrement operators: ++, --

Increment and decrement operators: ++, --


Increment and decrement operators in C programming are used to increase or decrease the value of a variable by one. They provide a convenient shorthand notation for performing these operations. Here are the increment and decrement operators in C:

1. Increment (++):

The `++` operator increases the value of a variable by one.

   Example:

   int num = 5;

   num++;  // Equivalent to num = num + 1; num becomes 6

   The `++` operator can be used as a prefix (`++num`) or a postfix (`num++`). When used as a prefix, the increment operation is performed before the value of the variable is used. When used as a postfix, the increment operation is performed after the value of the variable is used.

2. Decrement (--):

The `--` operator decreases the value of a variable by one.

   Example:

   int num = 5;

   num--;  // Equivalent to num = num - 1; num becomes 4

   Similar to the increment operator, the `--` operator can be used as a prefix (`--num`) or a postfix (`num--`).

Increment and decrement operators are commonly used in loops, such as `for` and `while`, to iterate over a sequence of values or perform repetitive tasks.

Example:

int num = 5;

printf("Initial value: %d\n", num);  // Output: Initial value: 5

num++;  // Increment by one

printf("After increment: %d\n", num);  // Output: After increment: 6

num--;  // Decrement by one

printf("After decrement: %d\n", num);  // Output: After decrement: 5

Increment and decrement operators provide a convenient way to modify the value of a variable by increasing or decreasing it by one.