Increment and decrement operators in C language

To change the value of a variable by 1, use the increment and decrement operators. They are frequently employed in control structures such as loops.

Operator
Description
Example
Equivalent to
++
Increment by 1
a++
a = a + 1
--
Decrement by 1
a--
a = a - 1
++
Prefix increment by 1
++a
a = a + 1
--
Prefix decrement by 1
--a
a = a - 1

The increment operator adds 1 to the value of the variable and stores the result in the same variable.

Example:

int x = 5;
x++;
printf("The value of x is %d", x); // Output: The value of x is 6

In this example, the value of x is first set to 5. Then the increment operator is used to add 1 to x, resulting in a new value of 6. The printf function is then used to display the new value of x.

The decrement operator subtracts 1 from the value of the variable and stores the result in the same variable.

Example:

int y = 10;
y--;
printf("The value of y is %d", y); // Output: The value of y is 9

In this example, the value of y is first set to 10. Then the decrement operator is used to subtract 1 from y, resulting in a new value of 9. The printf function is then used to display the new value of y.

Increment and decrement operators can also be used in expressions.

Example:

int a = 5, b;
b = ++a;
printf("a = %d, b = %d", a, b); // Output: a = 6, b = 6

In this example, the value of a is first set to 5. Then the prefix increment operator is used to add 1 to a and store the result in a. The value of a is then assigned to b, resulting in b also having a value of 6.