- It increments the value of the operand by 1 (one).
- The operand must be a variable.
- The value of variable x is initialized to 5.
- In x++, x is an operand and ++ is an operator. An operator is better known as post-increment.
- x++ increases the value of variable x by 1, that is value becomes 6
- printf(“%d “,x); prints 6
- In ++x, an operator is better known as pre-increment operator
- ++x again increases the value by 1, that is it becomes 7
- printf(“%d “,x); prints 7
Unary Operators
Operator requires operands to perform its operation. Unary operators are those, which takes one operand to perform its task.
Operator requires operands to perform its operation. Unary operators are those, which takes one operand to perform its task.
Unary + and –
These operators should not be misinterpreted as addition and subtraction operators. These are unary + and –, used to make significant positive or negative. For example -3, +4, -345 etc
These operators should not be misinterpreted as addition and subtraction operators. These are unary + and –, used to make significant positive or negative. For example -3, +4, -345 etc
Increment Operator
Example
int main()
{
int x=5;
x++;
printf("%d ",x);
++x;
printf("%d ",x);
return(0);
}
Output
6 7
The job of pre-increment and post-increment operators are the same but there is a difference in priority. Pre-increment has higher priority than post-increment. In fact, post-increment has the least priority among all the operators.
Example
Example
int main()
{
int x=5,y;
y=x++;
printf("%d %d",x,y);
return(0);
}
Output
6 5
6 5
There are two operators in an expression
y=x++
. The assignment operator (=) has higher priority than post-increment operator, therefore, the value of x is copied to variable y. The value of y becomes 5. Now post-increment operator increases the value of variable x by 1. The variable x becomes 6.
No comments:
Post a Comment