Unary operators in C++
The Unary operators in C++ use only a single operand. The unary operator is either specified before or after the operand depending on the usage. C++ provides the following unary arithmetic operators:
Negation operator
Increment operator and Decrement Operator
1. Negation Operator (-)
The negation operator negates the associated operand and returns the negated value of the associated operand. The negation operator is specified to the left of the operand.
Examples:
Int x;
X = -3
Here, the constant value 3 will be negated and assigned to the variable x.
int new, old = 5;
new = - old;
Here the value of the variable âoldâ is negated and assigned to the variable ânewâ. Hence, the variable ânewâ will be assigned the value -5.
2.
Increment (++) and decrement (--) operators
Consider that a school register is automated and with the entry of the details of every student, the student count is incremented by 1. The student count is associated to the variable âstd_countâ. This assignment is done using the following code statement:
Std_count = std_count+1;
For example, the same could be coded as:
Std_count++;
OR
++std_count;
The increment operator consists of two addition signs that follow each other without any spaces in between.
The decrement operator is the opposite of the increment operator. For instance, in the example, in case there was a student who was leaving the school, then when his details are deleted from the school register, the student count should also decrease by 1. This could be represented as:
Std_count=std_count â 1;
While using the decrement operator, the same is represented as:
std_count--; OR --std_count;
The decrement operator consists of two subtraction signs following each other without any spaces in between.
Using increment or decrement operators increases the readability of the code.
The difference between pre- and post- fixing the operator is useful when it is used in an expression. When the operator precedes the operand, increment or decrement operation takes place after using the value of the operand.
Consider the following,
a = 10;
b = 5;
c = a*b++;
In the expression, the current value of b is used for the product and then the value of b is incremented. That is, C is assigned 50 (a*b) and then the value of b is incremented to 6.
If however, the expression was
C = c * ++b;