C++ OPERATORS
The
different types of C++ operators and their usage are explained in the following
sections. In C++, there are some unusual operators used to perform the task of
logical decision making, unlike the other higher level languages.
C++ operators - Arithmetic operators
- Assignment operators
- Comparison and logical - Relational
operators - Equality
- Logical
- Bitwise logical operators
- Special operators -
Unary operators
Ternary
operators
Comma operators
Scope operators
New and delete
Other operators
Arithmetic
Operators
Arithmetic
Operators are the basis and common operations performed using any computer
programming. Normally, these operators are considered as basic operators and
known as binary operators as they require two variables to be evaluated. For
example, if we want to multiplier two numbers, one has to enter or feed the
multiplicand and the multiplier. That is why it is considered as a binary
operator. In C++, the arithmetic operators used are as follows:
Operators
|
Meaning
|
+
-
*
/
%
|
addition
subtraction
multiplication
division
modulo
(remainder of an integer division)
|
The operators /
(slash) for division deserved a special attention. If we divided an integer by
another integer, we obtain an integer value.
39/5 = 7
If in the division x/y
at least one of
the operands x and
y is of
floating point type, the subtraction and multiplication. For the letter
operations the value of the result is not seriously affected by the type of
operands.
For example,
4 + 3 = 7 (integer
type)
4.0 + 3.0 =7.0 (floating point)
x_integer / y_integer =
result_integer
x_integer / y_ float =
result_ float
x_ float / y_integer = result_ float
x_ float /y_ float = result_ float
39/7.0 = 5.57
39.0/7.0 = 5.57
39.0/7 = 5.57
39.0/7.0 = 5.57
The
result of the division obtained by the / operator is called the quotient.
Integer division has another interesting result, namely the remainder, obtained
by the operator %.
For example,
39 % 5
gives 4 ,
since 39 =
7*5+4
Expressions An expression is a collection of data object and operands
that can be evaluated to a single value. An object is a constant, variable, or
any other expression.
The most general form is,
objectl expression object2
The
result is a new data object.
For
example,
2+3 evaluates 5
3-7 evaluates -4
Note
that the use of the blanks has no effect on the evaluation of the expression.
The parentheses are used to improved readability of the program and also to
avoid user errors. That means, the evaluation should be carried out as per the
precedence rules defined in the C++ compilers.
Arithmetic operators as per precedence:
( ) for grouping the
variables
- (unary for negative number)
* / (multiplication and division)
+ - (addition and su8btraction)
For example, if the following expression is
not properly grouped using parentheses then the computer will evaluated as per
the precedence.
x + y * x – z where
x=5, y=6
and z=8
5 + (6 * 5) – 8
(5 + 30) -8
35 – 8
27
the result is27
Suppose,
if we intended to evaluate the above expression as (x+y) *
(x-z) then
the parentheses will be evaluated because it has the highest priority and the
result will be different from the previous expression.
(5+6) * (5-8)
11 * -3
-33
Assignment
Operators
An
assignment operator is used to assign back to a variable, a modified value of
the present holding.
Operators
|
Meaning
|
=
+=
-=
*=
\=
%=
>>=
<<=
&=
|=
~=
|
Assign right hand side
(RHS) value to the left hand side (LHS)
Value of LHS variable will
be added to the value of RHS and assign in back to the variable in LHS
Value of LHS variable will
be subtracted from the value of LHS and assign in back to the variable in LHS
Value of LHS variable will
be multiplied by the value of RHS and assign in back to the variable in LHS
Value of LHS variable will
be divided by the value of RHS and assign in back to the variable in LHS
The remainder will be
stored back to the LHS after integer division is carried out between the LHS
variable and the RHS variable
Right shift and assign to the LSH
Left shift and assign to
the LHS
Bitwise AND operation and
assign to the LHS
Bitwise OR operation and
assign to the LHS
Bitwise complement and
assign to the LHS
|
The symbol = is used as an assignment operator
and it is evaluated at the last. Remember that equal to (=) is an operator and
not an equation maker and hence, it can appear anywhere in place of another
operator. The following are valid C++ statements.
a = b =
c+4;
c = 3* (d
= 12.0/x);
For example,
x += y is
equal to x= x+y
x -= y is equal
to
x = x-y;
Comparison and
Logical Operators
For
program flow, the comparisons as well as the logical operators are required.
The com parison and logical operators can be grouped into three. They are
relational operators, equality operators and logical operators.
Operators
|
Meaning
|
<
>
<=
>=
==
!=
&&
|
|
!
|
Less
than
Greater
than
Less
than or equal to
Greater
then or equal to
Equal
to
Not
equal to
Logical
AND
Logical
OR
Not
|
(a) Relational
operators Relational operators compare
values to see if they are equal or if one of them is greater then other and so
on. For program flow, the comparators and the logical operators are essential
Relational operators in C++ produce only a one or a zero result. These are
often specified as “true” or “false” respectively, since these are the only two
values possible. The following operators are used to perform the relational
operations of the two variables or expressions.
Operators
|
Meaning
|
<
>
<=
>=
|
Less than
Greater than
Less than or equal to
Greater then or equal to
|
The
relational operators are represented in the following syntax,
expressionl
relational_operator expression2
The
expressionl will be compared with expression2 and depending upon the
relation like greater then, greater then or equal to and so on, the result will
be either “true” or “false”
For example,
Expression
|
Result
|
3 > 4
6 <= 2
10 > -32
(23*7) >= (-67+89)
|
false
false
true
true
|
(b) Equality
operators The following operators are used to check the
equality of the given expression or a statement. These operators are normally
represented by using the two keys, namely, “equal to” by the operator == and
“not equal to” by !=. Not that the single “equal to” sign is considered as an
assignment operator in C++. Proper care must be taken while using these
operators.
Operators
|
Meaning
|
=
=
!
=
|
Equal to
Not equal to
|
Like the relational operators, the equality
operators also produce the result, either “true” or “false”, depending on the
condition used in a program. The following examples show the usage of equality
operators.
For example, a = 4, b = 6, and
c = 8
Expression Result
a = = b false
(a*b) ! = c true
‘s’ = = ‘y’ false
(c) Logical
operators The logical operators
&& and | | are lower in precedence then the relational operators <
and >, which in true are lower than + and -. The operator && is
higher in precedence than the operator | |. In some other languages, the
logical operators are placed higher than the relational operators, which
require parentheses.
Operators
|
Meaning
|
&&
|
|
!
|
Logical
AND
Logical
OR
Not
|
(i) logical
AND A compound expression is true when two
conditions (expressions) are true. To write both condition, the operator
&& is used in the following manner,
expressionl && expression2
In the two expressions, the conjunction must
be integers. The char data are converted to integer and are thus allowed in the
expression.
The result of logical operators are :
Situation
|
Result
|
true && true
true && false
false && true
false && false
|
true
false
false
false
|
For
example,
a = 4, b = 5,
and c = 6
(a <
b) && (b < c)
(4 <
5) && (5 < 6)
true && true
true
(ii) Logical OR similar to the logical
AND is the logical OR, which has the form;
expressionl | | expression2
and evaluates to true if either expressionl or expression2 is true.
The
result of logical OR operators are:
Situation
|
Results
|
true
| | true
true
| | false
false
| | true
false
| | false
|
true
true
true
false
|
For
example,
a = 4, b = 5 , and
c = 6
(a < b ) | | (
b > c )
(4 < 5 ) | | (
5 > 6 )
true | | false
true
In the logical OR operator, if one of the
expression is true, then it yields true.
(iii) Logical
negation operators A logical expression can be
changed from false to true or from true to false with the negation operator !.
The result of logical negation operators
are
Situation
|
Results
|
!
(true)
!
(false)
|
false
true
|
The
general form of the expression
! (expression)
Depending
on the condition of the expression, i.e., whether it is true or false, it will
complement the result.
For example,
a = 4, b = 5, and c = 6
(1)
! (a < b ) | | ( c > b )
! (4 < 5 ) | | ( 6 > 5 )
! ( true)
| | true
false | | true
true
This
expression evalutes to true.
(2)
! ((a < b ) | | (b > c))
! ((4 < 5) | | (5 > 6))
! (true
| | false)
!
(true)
false
The above expression evaluates to false.
The negation operator has a higher level of
precedence then && and | |. Parentheses are usually necessary to reduce
unwanted or unexpected results. Since the logical AND has a higher precedence
over the logical OR, care should be taken to use parentheses wherever required.
For example,
expressionl | | expression2 && expression3 | | expression4
In the computer the above will be evaluated as
expressionl | |( expression2
&& expression3) | | expression4
Suppose it is intended to evaluated the above compound
expression as
(expressionl | | expression2)
&& (expression3 | |
expression4 )
then,
it is advisable to use parentheses to avoid undesirable results.
For example,
a = 4, b = 5, and c = 6
(1)
(a < b) | |
(b > c) && (a
>b) | | (a > c)
(4 < 5) | | (
5 > 6) && ( 4 > 5) | | ( 5 > 6)
true | | false && false | | false
true | | (false && false) | |
false
true | | false | | false
true | | false
true
The logical And has a higher precedence over
the logical OR and that is why the above expression evaluates to true.
(2)
( (a < b) |
| (b > c) ) && ( (a >b) | | (a > c))
( (4 < 5) | | ( 5 > 6) ) &&
( (
4 > 5 ) | | ( 5 > 6) )
(true | | false) &&
(false | | false)
true && false
false
To
avoid unpredicted or undesirable result it is better that the parentheses are
used. For those who are familiar with FORTRAN or PASCAL, the following
comparison between the notations for some operators may be helpful.
FORTRAN PASCAL
C++
= : = =
.EQ. = = =
.NE. <> ! =
.LT.
< <
.GT. > >
.LE. <= <=
.GE. >= >=
.AND. and &&
.OR. or | |
.NOT. not
!
/
/ div /
Bitwise
Logical Operator
There
are certain situations wherein bitwise operations are to be performed, and this
is possible in C++. The following operators are used for the bitwise logical
decision making. Normally, most of the high level programming languages does
not support the bitwise operations. The bitwise operators are one of the
salient features of C++. The following operators can be performed using bitwise
operators:
·
bitwise
AND
·
bitwise
OR
·
bitwise
exclusive OR
·
bitwise
left shift
·
bitwise
right shift
·
bitwise complement
Operator
|
Meaning
|
&
^
|
>>
<<
~
|
Bitwise AND
Bitwise exclusive OR (XOR)
Bitwise inclusive OR
Bitwise left shift
Bitwise right shift
Bitwise complement
|
(a) Bitwise complement
The
complement operator ~ switches all the bits in a binary pattern, that is, all
the zeroes become ones and all the ones become zeros. The complement of a pattern is often useful in signaling and
controlling other devices where several different signals may be complementary
to each other. The following example show how the bitwise complement works:
Variable
|
Value
|
Binary Pattern
|
x
~x
y
~y
|
23
132
ff
00
|
0001 0111 (8 bits)
1110 1000
1111 1111
0000 0000
|
(a) Shift operations The shift operations take
binary patterns and shift the bits to the left or right, keeping the same
number of bits by dropping shifted bits off the end and filling in with zeroes
from the other end. C++ provides two types of shift operations, left shift and
right shift.
(i)
Left shift The<<operator is used for left shifting.
Variable Value Binary Pattern
x 33 0010 0001 (8 bits)
x << 1 - the bit pattern of the x value is left shifted
once.
x = 33 and the bit pattern is 0010 0001
x << 3 the bit pattern of the x value is left shifted by
thrice.
0 0 1 0 0 0 0 1
0 0 1 0 0 0 0 1 0
0 1 0 0 0 0 1 0 0
1 0 0 0 0 1 0 0 0
The
resultant bit pattern will be
0 0 0 0 1 0 0 0
(ii) Right shift
The
right shift >> operator is used for right shifting.
For y = 41, the bit binary pattern is
0010 1001
For y >> 3, the bit pattern of the y value is right shifted by
thrice.
0 0 1 0 1 0 0 1
0 0 0 1 0 1 0 0 1
0 0 0 0 1 0 1 0 0
0 0 0 0 0 1 0 1 0
The
resultant bit pattern will be
0 0
0 0 0 1 0 1
(c) Bitwise
logical operators The following are the
bitwise logical operators.
- bitwise
- bitwise OR
- bitwise exclusive OR
(i) Bitwise AND The bitwise AND operation will be carried out
between the two bit patterns of the two operands. For example,
Variable
|
Value
|
Binary Pattern
|
x
y
x & y
a
b
a & b
|
5
2
0
6
3
2
|
0101
0010
0000
0110
0011
0010
|
To generate a l bit in the result, bitwise
AND need a one in both numbers. Masking bits can be done using AND. The most
useful part of the bitwise operations is a bitwise AND. Normally, it is called
a mask operator and one may select the particular pattern as either a one or a
zero and it select certain specific bits and ignores the others.
(ii) Bitwise OR
The
bitwise OR operations are similar to the bitwise AND and the result is l if any
one of the bit value is l. The symbol |
represent the bitwise OR.
For
example,
Variable
|
Value
|
Binary Pattern
|
x
y
x | y
a
b
a | b
|
5
2
7
6
1
7
|
0101
0010
0111
0110
0001
0111
|
(iii) Bitwise exclusive OR the bitwise exclusive OR will be carried out by the
notation^.
To generate a l bit in the result, a bitwise exclusive OR needs a one in either
number but not both.
Variable
|
Value
|
Binary Pattern
|
x
y
x ^ y
a
b
a ^ b
|
5
2
7
6
3
5
|
0101
0010
0111
0110
0011
0101
|
All
the bitwise operators may appear with the assignment operator just like the
arithmetic operators discussed earlier.
Expression Meaning
n
>>= 1 n = n >>
1
n will be shifted right by 1
and than assigned back to
variable n
a
<<b a = a
<< b
the content of the a
will be shifted left by the content of
b and the assigned back to a
x &=
4 x = x
& 4
i ^= 4 x = x & 4
j |= 5
j = j | 5
Special Operators
There
are some special operators used in the C++ language to perform particular type
of operation. The following operators are considered as unary operators in the
C++ language.
(a) Unary operators The unary operators require only a single expression to
produce a line. Unary operators usually precede their single operands.
Sometimes, some unary operators may be followed by the operands such as
incrementer and decrementer. The most common unary operation is unary minus,
where minus sign precedes a numerical constant, a variable or an expression.
The following
operators are the unary operators in C++:]
Operator
|
Meaning
|
*
&
-
!
~
++
--
type
sizeof
|
Contents of the storage
field to which a pointer is pointing ( refer chapter 6)
Address of a
variable (refer chapter 6)
Negative
value (minus sign)
Negation (
0.if value # 0, l ,if value =0)
Bitwise
complement
Incrementer
Decrementer
Forced type of conversion
Size of the subsequent
data type or type in byte
|
(i)
Pointer operator (*) The pointer operator is used to get the content of the
address operator pointing to a particular memory element or cell.
(ii)
Address operator(&) The address operator & is used to get the address of
the other variable in an indirect manner. The pointer operator (*) and the
address (&) are explained in Chapter 6 on “pointers.”
(iii)
Size of operator The sizeof operator is used to give the direction to the C++ compiler
to reserve the memory size or block to the particular data type which is
defined in the structure type of the data in the linked list. This operators
are explained in chapter 7 on “structures, Unions and fields.”
(iv)
Incrementer and
decrementer Two special operators are
used in C++, namely, incrementer and decrementer . These operators are used to
control the loops in an effective manner.
Incrementer: The ++ symbol or notation is
used for incrementing by 1.
For example,
++i; is equal
i
= i+l;
i++;
is equal to
i
= i+l;
There are two type of incrementers: prefix incrementer (++i) and postfix incrementer (i + +). For the time being, let us
take it that they can be used according to a programmer’s liking but there are
some special condition under which these incrementers are used very
particularly.
In prefix incrementer, first it is
incremented and then the operations are performed. On the other hand, in the
postfix incrementer, first the operations are performed and then it is
incremented. However, the result of the incremented value will be the same in
both the causes.
For example,
i = 7;
x = ++I;
x = i++;
After execution, the value of x will be set
to 8.
Decrementer: The decrementer is also similar to the
incrementer. The – symbol or notation is used for decrementing.
For example,
--i is equal to i = i-l
i--
is equal to
i
= i-l;
In this also there are two types of
decrementers, prefix decrementer ( --i ) and postfix decrementer ( --i ).
(v) Cast operator There are situations,. Where some variable are declared as
integers but sometimes it may be required to get the result as floating point
numbers. The type provides a specific and a special way for converting one data
type to the other using a cast operator.
(b) Ternary
operator (?:) C++ includes a very special operator called the ternary or
conditional operator. It is called ternary because it uses expressions. The
ternary operator acts like a shorthand version of the if-else construction. The general format
of the ternary operator is:
expressionl
?expression2 : expression 3
Which
results in either expression2 or expression3 is evaluated. The conditional
operator is used in place of a single if-else
to make an
assignment.
For Example
if ( value % 2 == 0 )
even =
true
else
even =
FALSE;
This
can be written as
even =
(value % 2 == 0 ) ? TRUE : FALSE ;
Another
example would be to find the large of two number,
if (first
> second)
max =
first ;
else
max =
second;
This
can be written as
max = (
first > second ) ? first : second ;
(c) Comma operator C++ uses the comma in two ways. The first use of comma is
as a separator in the variable declaration.
int a,b,c;
float x,y,z;
Another
use is as an operator in an expression for loop. It is explained in detail in
the chapter 3 on “Control statements”.
(d) Scope operator(::) The double colon : : is used
as the scope resolution operator in C++. The scoping operator is also used in a
class member function definition. The scope operator can also be used to
differentiate between member of base classes with identical names. It is
explained detail in the chapter 8 on “Classes and objects”.
(e) New and delete
operators in traditional C, the
dynamic memory allocations and deallocations are handled through library
functions such as malloc, alloc, calloc and free routines. C++ defines a new
and delete operators.
(f) Other
operators
(i) Parentheses for grouping expressions
(ii) Membership operators
Parentheses
for grouping expressions () The precedence and
associativity of each operator determines whether it takes effect before or
after the next operator in an expression. Often, it is more convenient control
this order of evaluation. When parentheses are put around an element of an
expression, the element evaluates before anything outside the parentheses.
For example,
(a+b)* c wpuld cause the addiotion
to be performed the multiplication, whereas a+b*c would cause the
multiplication to be performed.
Membership
operator There are several kinds of
variables used in C++, containing a set of values, membership operator are
used, which are represented as [] ->
c language code snippets for programmers
ReplyDeletesample c code - Binary search int array