Increment & decrement operators
In C, the increment (++
) and decrement (--
) operators are used to increase or decrease the value of a variable by 1, respectively. These operators are often used to perform repetitive tasks, such as iterating through arrays or loops, and they can be applied to both integer and floating-point variables.
Here's how the increment and decrement operators work:
1. Increment Operator (++):
2. Decrement Operator (--):
It's important to note that the use of post-increment, post-decrement, pre-increment, or pre-decrement can lead to different behavior in expressions and statements. For example, in an assignment statement or within a larger expression, the choice of pre-increment or post-increment can affect the result.
Here's an example that illustrates both pre-increment and post-increment:
#include <stdio.h>
int main() {
int num = 5;
printf("Initial value: %d\n", num);
int postResult = num++;
int preResult = ++num;
printf("After post-increment, num = %d, postResult = %d\n", num, postResult);
printf("After pre-increment, num = %d, preResult = %d\n", num, preResult);
return 0;
}
Output:
Initial value: 5
After post-increment, num = 7, postResult = 5
After pre-increment, num = 7, preResult = 7
This example demonstrates the difference between pre-increment and post-increment, and how they affect the value of the variable and the result of the expression.