|
You are familiar with + and – symbols we use in basic mathematics for addition and subtraction between two numbers. The unary + and - operators are different than those symbols. They do not add or subtract. Instead they are used to represent the sign of the operand. Unary + as such has no significance because the numeric literals are positive by default. If you apply it to a numeric literal, it will only emphasize its positive nature. The unary – negates the numeric literal. You can apply these operators as:
int a, b, c;
a = +5; // Unary + to emphasize the positive sign
b = -4; // Unary - to negate the value
Besides numeric literals you can also apply the unary + and – to expressions. If you see a negated expression, you can evaluate its value by first evaluating the value of the expression and then negating it. Following example shows how the unary – is used to negate expression (b-3):
c = -b; // Unary - to negate expression, c is 4
d = -(b – 3); // Unary - to negate expression, d is 7
Since value of b is -4, the expression –b will be -(-4). Therefore, the value of c is evaluated as 4. Similarly, the expression (b-3) is evaluated to -7 and then the unary – will negate it. Therefore the value of d will be 7.