How Unary Operator Works?

Unary operators are called so because they need only one operand to work.

We have increment ++ and decrement -- operators which can be used as either postfix or prefix.

  • Postfix unary operator first gives output the the value itself and then does the operation.
  • Prefix unary operator first does the operation and then gives output the final result.


Examples

If we do a++ then it will first give output as a and then increase the value of a to a+1. But if we do ++a then it will first increase the value to a+1 and give final result output.

Increment Operator

If, a = 5             | If, a = 5
&   b = a++           | &   b = ++a
                      |
Then,                 |Then,
it returns: a = 6     |it returns: a = 6
&           b = 5     |&           b = 6
Decrement Operator
If, a = 5             | If, a = 5
&   b = a--           | &   b = --a
                      |
Then,                 |Then,
it returns: a = 4     |it returns: a = 4
&           b = 5     |&           b = 4