There are two special arithmetic operators called increment and decrement operators available C. They are unary operators unlike all other arithmetic operators. The operators are denoted as : '++' (increment operator), '--' (decrement operator).
Operator | Name | Description | Example |
---|---|---|---|
++ | Increment Operator | Increments the value of operand by 1 | a++ : This is equivalent to a = a + 1 |
-- | Decrement Operator | Decrements the value of operand by 1 | a-- : This is equivalent to a = a - 1 |
Variants of Increment and Decrement Operators - Pre Increment, Post Increment, Pre Decrement and Post Decrement
There are two different variants of increment and decrement operators known as pre increment, post increment, pre decrement and post decrement operators.
- Pre Increment Operators: When '++' is used as prefix of the operand, it's called pre increment operator. Pre increment operator will increment the value of operand before using it in the expression.
- Post Increment Operators: When '++' is used as postfix of the operand, it's called post increment operator. Post increment operator will increment the value of operand after using it in the expression. ie; The current expression will use non-incremented value of operand.
- Pre Decrement Operators: When '--' is used as prefix of the operand, it's called pre decrement operator. Pre decrement operator will decrement the value of operand before using it in the expression.
- Post Decrement Operators: When '--' is used as postfix of the operand, it's called post decrement operator. Post decrement operator will decrement the value of operand after using it in the expression. ie; The current expression will use non-decrement value of operand.
Examples of pre increment, post increment, pre decrement and post decrement operators are given below
- #include <stdio.h>
- int main(void) {
- int a = 5;
- // Pre increment operator. Value of 'a' will be incremented first and then
- // used in the expression. So b is assigned value after a gets incremented.
- int b = ++a;
- printf("a = %d, b = %d\n", a, b);
- a = 5;
- // Post increment operator. The value of 'a' will be incremented only after
- // it gets used in the expression. That means, first b will get assigned the
- // value of 'a' and then value of 'a' will be incremented .
- b = a++;
- printf("a = %d, b = %d\n", a, b);
- a = 5;
- // Pre decrement operator. Similar to pre increment operator, pre decrement
- // operator decrements the value of operand before using it in the expression.
- b = --a;
- printf("a = %d, b = %d\n", a, b);
- a = 5;
- // Post decrement operator. Similar to post increment operator, post decrement
- // operator decrements the value of operand after using it in the expression.
- b = a--;
- printf("a = %d, b = %d\n", a, b);
- return 0;
- }
- Output:
- a = 6, b = 6
- a = 6, b = 5
- a = 4, b = 4
- a = 4, b = 5
No comments:
Post a Comment