Page 34 - DCAP404 _Object Oriented Programming
P. 34
Unit 2: Beginning of OOP Language
2.3.3 Unary Operators Notes
Operator Description Example Explanation
++ Increases the value of the a++ Equivalent a = a+1
operand by one
– Decreases the value of the a- Equivalent to a = a-1
operand by one
The increment operator, ++, can be used in two ways - as a prefix, in which the operator precedes
the variable.
++var;
In this form the value of the variable is first incremented and then used in the expression as
illustrated below:
var1=20;
var2 = ++var1;
This code is equivalent to the following set of codes:
var1=20;
var1 = var1+1;
var2 = var1;
In the end, both variables var1 and var2 store value 21.
The increment operator ++ can also be used as a postfix operator, in which the operator follows
the variable.
var++;
In this case the value of the variable is used in the expression and then incremented as illustrated
below:
var1 = 20;
var2 = var1++;
The equivalent of this code is:
var1 = 20;
var2=var1;
var1 = var1 + 1; // Could also have been written as var1 += 1;
In this case, variable var1 has the value 21 while var2 remains set to 20.
In a similar fashion, the decrement operator can also be used in both the prefix and postfix
forms.
If the operator is to the left of the expression, the value of the expression is modified before the
assignment. Conversely, when the operator is to the right of the expression, the C++ statement,
var2 = var1++; the original of var1 is assigned to var2. In the statement, var2 = ++var1++; the
original value of var1 is assigned to var2. In the statement, var2 = ++var1; the incremented value
of var1 is assigned to var2.
LOVELY PROFESSIONAL UNIVERSITY 27