You are on page 1of 19

CHAPTER

4.1 INTRODUCTION

Operators are instructions, represented by a single symbol or combination of symbols such as


+, , /, +=, &, etc., which are used in program statements to carry out some action on the data.
The actions may be assignment, arithmetic operations, comparison of values of two variables,
determination of address of a variable, pointing to memory location or linking an object to its
class member, etc. C++ has a rich inventory of operators, however, in this chapter we shall be
dealing with the following.
(i) Assignment operators
(ii) Arithmetic operators
(iii) Composite assignment operators
(iv) Increment & decrement operators
(v) Relational or comparison operators
(vi) Logical operators
(vii) Bitwise logical operators
Most of these operators are common with those of C. The symbols of these operators are
shown in Table 4.1. Some of these we have already used in previous chapters, however, we have
not examined their behaviour in detail.
C++ supports unary, binary and ternary operators. A unary operator takes one operand for
its operation, a binary operator takes two operands and a ternary operator takes three operands.
There is only one ternary operator in C++, i.e. selection operator (?:) which is discussed in the
next Chapter. Examples of operators which are both unary and binary are + and . These
operators may be used to change the sign of a value in which case these are unary operators. These
may also be used to add and subtract two quantities in which case they operate on two quantities
and are binary. The arity of an operator is the number of operands it takes for its operation.

OPERATOR PRECEDENCE AND ASSOCIATIVITY


Consider the following simple calculation.
8 - 2*3
78 Programming with C++

We know that its result is 2. But how is that result calculated? We first multiply 2 and 3
and then subtract the product (6) from 8. That means that multiplication has higher priority
or precedence than the minus, otherwise if we first subtract 2 from 8 and then multiply the result
would be 18. Each operator has a precedence level which decides its turn for operation when
there are several operators in a statement. The operator with highest precedence is performed first
followed by the one with the next lower precedence. The precedence levels of the operators are
set in the complier and computer follows these rules during calculations.
Now if a number of operators having the same precedence level are there in a statement then
how to decide as to which should be performed first. For example consider the following
calculation.
20 % 3 * 5
The operators % and * have same level of precedence and both are binary operators. In the
previous chapter we studied the modulus operator (%) which gives the remainder on division. Thus
20 % 3 = 2. In the above expression, if operation 20%3 is performed first the result is 10, otherwise
if 3*5 is performed first the result is 5 because in that case 20 %15 = 5. In such cases the
associativity of the operators comes to rescue. Since the operators are binary if the operations are
performed left to right the result is 10 and if it is performed right to left the result is 5. The
associativity of both % and * operators is left to right and thus the correct result is 10.
The operators in C++ are implicitly defined for variables of fundamental types. For user
defined types such as class objects, C++ allows to redefine their functionality so that they can
be used for class objects as well. The examples are (i) manipulations of vectors, (ii) manipulation
of complex numbers, etc. For such cases the operators are overloaded (functionality is redefined)
Even if the functionality of an operator is redefined (see Chapter 13 ) the arity, the precedence
and the associativity of the operator do not change.

4.2 ASSIGNMENT OPERATOR

The basic assignment operator is ( = ) which is often called equal to. On the left of this operator
we write the name of variable to which a value is to be assigned or l-value and on right side we
write the value to be assigned to it or r-value. The l-value is the memory space in which the r-
value is stored. Consider the following assignments.
int x = 5; // Declaration and initialization
int y = 10;
y = x ; // assignment
In the last statement, will the value of x be assigned to y or the value of y be assigned to x?
The associativity of = operator is right to left, so value of x will be assigned to y. In this operation
y becomes 5.
In the previous chapters we have already studied the two methods of declaration and
initialization, which are illustrated below.
type identifier = value ;
type identifier ( value) ;
Operators 79

The example are given below.


int x = 5, n = 3;
We may write such statements as given below.
int x , Age; // declaration
float y ; // declaration
y = 5.764; // assignment
x = 5; // assignment
Age = 22; // assignment
The second method is illustrated below. .
int Age(22) ; // Age is declared and initialized to 22.
Similarly a floating point variable may be declared and assigned as below.
float PI(3.14159);
double PI(3.1415926535);
Let Kh be name of a variable of type character. We want to assign the character B to it.
We may write the code as below.
char Kh;
Kh = B;
Or we may combine the above two statements as below.
char Kh = B;
or as,
char Kh(B);

Similarly a string of characters may be assigned. In the following the <string> header file is
included in the program in order to declare variables of type string.
#include<string>
void main()
{string myname ; // myname is a variable of type string
myname = Monika; /*Monika is the value assigned to myname */
string Name (Sujata); // Name is assigned value Sujata
string name = Mamta; }
However, if the header file <string> is not included, a string variable may be declared as C-
string. For such a case the assignment is illustrated below.
char myname [] = Monika;
The constant 0 (zero) is of type int, however, it may be assigned to variables of all types.
Thus we can write as below.
80 Programming with C++
int x = 0; // It assigns 0 to int x.
float y = 0; // It assigns 0.0 to float y
double d = 0; //It assigns 0.0 to double d
char ch = 0; //It assigns Null character \0 to ch,

Table 4.1 Operators common to C and C++

Operator Description of Operator Description of


symbol action symbol action

Arithmetic operators , Evaluate


+ Addition Increment/
decrement
Subtraction ++ Increment by 1
* Multiplication Decrement by 1
/ Division Logical operators Also see chapter5
% Modulus && AND
Assignment operators || OR
= Assignment ! NOT
+= Add and assign Bitwise operators
= Subtract and assign & AND
*= Multiply and assign | OR
/= Divide and assign ^ XOR
%= Assign remainder >> Shift right
Relational operators Also see chapter 5 << Shift left
== Equal to ~ complement
> Greater than &= Bitwise AND assign
< Less than |= Bitwise OR assign
!= Not equal ^= Bitwise XOR assign
>= Greater than or equal <<= Bitwise shift left
and assign
<= Less than or equal >>= Bitwise shift Right
and assign
?: Conditional operator

Programs 4.1 and 4.2, given below, illustrate the assignment of different types of variables.

PROGRAM 4.1 Illustrates different methods of assignments.

#include <iostream>
using namespace std;
Operators 81
void main()
{int P(20); // This is equivalent to int P = 20;
int M = 30;
cout<<P = <<P<<,t M = <<M<<endl;
double C (4.56), D ; // double C(4.56) is equivalent to
// double C = 4.56
D = 6.54;
cout<< C = << C<<,t D = <<D<<endl;

char Kh(B); // For assigning single char the single


// quotes are required
char ch = A;
cout << Kh = << Kh << ,t ch = << ch <<endl;
}

The expected output is as below

P = 20, M = 30
C = 4.56, D = 6.54
Kh = B, ch = A

The following program makes use of <string> header file which provides similar assignment
operations as we do for int or char variables.

PROGRAM 4.2 For a string of characters we may use class string (see Chapter 17).

#include <iostream>
using namespace std;
#include <string>
void main()
{ // In following Name1, Name2 and Name3 are names of strings.
string Name1(Mona Lisa); // string of characters have to be
// put in double quotes
string Name2 = Gyatri;
string Name4 = Malhotra;

string Name3;
Name3 = Raman; //Assignment = can be used for objects
//of class string.
cout << Name1 = << Name1 <<endl;
cout << Name2 = << Name2 <<endl;
cout<< Name3 = << Name3 <<endl;
cout << Name2 + Name4 = << Name2 + Name4<<endl;
}
82 Programming with C++

The expected output of the program is given below. Note that we have used header file <string>
in the program. The objects of this class may be added as illustrated in last line.
Name1 = Mona Lisa
Name2 = Gyatri
Name3 = Raman
Name2 + Name4 = Gyatri Malhotra

4.3 ARITHMETIC OPERATORS

We have already discussed the arithmetic operators in Chapter 3. The different arithmetic
operators are +, , *, / and % which represent the addition, subtraction, multiplication, division
and modulus. The application of these operators has also been illustrated in Program 3.13 in the
previous chapter. The operator % is applicable only to integers and is generally used to test the
divisibility of a larger integer by a smaller integer. If on division the remainder is zero then larger
number is divisible by the smaller number. The following program illustrates the test of
divisibility.

PROGRAM 4.3 Illustrates the test of divisibility of integers.

#include<iostream>
using namespace std;

void main()
{ int A,B, m;

cout<< Enter two integers :; cin >> A >>B;


cout << you have entered A = <<A << and B = << B<<endl;

if (A %B ) //the condition is if A%B is more than zero


cout<<A is not divisible by B <<endl;
else
cout <<A is divisible by B <<endl;
}

The expected output is as under. Two numbers 64 and 2 are entered. 64 is divisible by 2.
Enter two integers :64 2
you have entered A = 64 and B = 2
A is divisible by B

The following program calculates the roots of a quadratic equation ax2 + bx + c = 0. Because
this involves the evaluation of square root so the header file <cmath> is included in the program.
Operators 83
PROGRAM 4.4 The program calculates roots of a quadratic equation.

#include <iostream>
#include <cmath> //<cmath> header file is required for
//calculating square root
using namespace std;
int main()
{ // quadratic equation is: a x2 + bx + c = 0
double a,b,c, P, S;
cout << Enter the values of a,b and c :;
cin>>a>>b>>c;

P = b*b-4*a*c ;

if( P < 0) // If P is ve, the roots are imaginary.


{ P = -P;
S = sqrt(P)/(2*a);
cout<<Root R1 = << b/(2*a) <<+ <<i<<S << and Root R2 =
<< b/(2*a)<< <<i<<S<<endl;
}
else
{ S = sqrt(P) ; // If P is +ve the roots are real.

cout <<Root R1= << (b+ S)/(2*a) <<, and Root R2 = << (b
S)/(2*a) <<endl;
}
return 0;
}

The following two trials of the above program are carried out with different values of a, b and
c. In the first case imaginary roots are obtained and in second case real roots are obtained.
Enter the values of a,b and c :4 10 10.25
Root R1 = 1.25+i1 and Root R2 = 1.25i1
The following real roots are obtained when we enter a = 4, b = 10 and c = 4.
Enter the values of a,b and c :4 10 4
Root R1= 0.5, and Root R2 = 2

PRECEDENCE IN ARITHMETIC OPERATORS


All the arithmetic operators do not have the same precedence. Computer first evaluates those with
highest precedence then it evaluates those with next precedence and so on. Table 4.2 gives
precedence of arithmetic operators.
84 Programming with C++
Table 4.2 Arithmetic operators

Arithmetic operation C++ operator Order of evaluation


Parentheses () First. If there are several nested pairs,
the inner most pair is evaluated first.
If in parallel, from left to right.
Multiplication, division, * / % Equal. If there are several than left to
modulus right
Addition, Subtraction + Equal, If there are several from left to
right

Below is an illustration of how an expression for A is evaluated by computer.


A = 5*((3 + 4) +6) 2 *(3+4);
= 5*(7 + 6) 2*(3+4)
= 5*13 2*(3+4)
= 5*13 2*7
= 65 2*7
= 65 14
= 51
In some cases when the expressions are not written carefully the precedence may give an
unexpected result. This is demonstrated by following program.

PROGRAM 4.5 Illustrates the effect of precedence on the value calculated.

#include <iostream>
using namespace std;

int main()
{
int a = 15, n = 3,s = 8, p = 6,r = 3,A ,B , P1,P2,P3 ;
double C,D;
A = n*a%p ; // here first n and a are multiplied before
//the operation of %.
B = n*(a%p); // here () is evaluated first and the result
//is then multiplied to n.
P1 = n% a*p ;
P2 = (n%a)*p ;

P3 = n%(a*p);

C =(n +s +p +a)/r; //bracket is evaluated first


Operators 85
D = n + s+p+a/r; //Here a/r is evaluated first. It is
// then added to n+s+p.
cout<< A = << A <<\t B = << B <<endl;
cout<< P1 = <<P1<<\t P2 = << P2 <<\tP3 = << P3<<endl;
cout <<C = << C <<\t D = << D << endl;
return 0;
}

The expected output is given below.


A = 3 B = 9
P1 =18 P2 = 18 P3 = 3
C = 10 D = 22
The above program emphasizes how the precedence can make a difference in the calculation.
Let us take the line,

A = n * a % p ;
Though the precedence level of * and % is same but evaluation is from left to right so the
above expression is equivalent to the following.
A = (n * a) % p ;
Therefore, the expressions A = (n * a) % p; and A = n *( a % p); would not give same
result. Same is true for evaluation of P1, P2 and P3. The expression P1 = n%a*p ; is equivalent
to the following.
P2 = (n%a)*p ;
But P3 = n%(a*p); is different because the priority has been changed. In this the expression
(a*p) is evaluated first.

4.4 COMPOSITE ASSIGNMENT OPERATORS

C++ allows combining the arithmetic operators with assignment operator. The arithmetic
operator is written first followed by assignment operator but not vice versa. Thus we write the
code for add and assign as below,
B += 6;
which means that first add 6 to the present value of B and then assign the result to B. This is
equivalent to the following statement.
B = B + 6;
Similarly the other operators may also be combined. All the composite operators are listed
in Table 4.3. The applications of some of these are given in the Program 4.6.
86 Programming with C++

Table 4.3 Composite assignment operators

Operator C++ expression Equivalent expression Explanation and use


+= B += 5; B = B +5; int B= 4;
B +=5 ; // makes B=9.
= C = 6; C = C 6; int C = 10;
C = 6 ; // makes C=4
*= D *= 2; D = D*2; int D = 10;
D *=2; // makes D=20
/= E /= 3; E = E/3; int E = 21;
E /=3; //makes E = 7
%= F %= 4; F = F % 4 ; Divides F by 4 and remainder
is assigned to F

In all the composite operators there should not be any space between the symbols. For instance,
if we give space between + and = such as + = it may result in error.

PROGRAM 4.6 The program illustrates the application of composite operators.


#include <iostream>
using namespace std;
int main ()
{
int m =3, n=4, p=5, s = 6, q = 11;
m += 2; // no space between + and =
n *= 4;
p = 3;
s /=2;
q %=4;
cout <<m = <<m <<, n = <<n<<, p = <<p<<, s = <<s<<endl;
cout << q = << q << endl;
return 0;
}

The expected output is given below. The out put is self explanatory.
m = 5, n = 16, p = 2, s = 3
q = 3

4.5 INCREMENT AND DECREMENT OPERATORS

For increasing and decreasing the values of integral objects by unity, we may make use of
increment operator ++ and decrement operator respectively. These operators may be placed
before or after the variable name. When the operators ++ and are placed before the variable
name, these are called pre-increment and pre-decrement operators respectively. When the
operators are placed after the names then these are called post-increment and post-decrement
operators. In case of pre-increment the present value of variable is first increased by unity and
the incremental value is then used in the application. And in case of post-increment, the present
Operators 87

value of variable is used in the application and then the value of variable is incremented. Same is
the case of operator . The pre and post versions of ++ and are also elaborated in Table 4.4.
Also take care that there should not be any space between ++ or between because this may
result in error.
Table 4.4 Increment and decrement operators

Pre or post Operator Description


Pre-increment ++ k First increase the value of k by unity. Then evaluate
current statement / function by taking incremented
value.
Post-increment k++ First use the current value of k to valuate current
statements / function, and then increase k by unity
Pre-decrement k First decrease the value of k by unity and assign it
to k. Then evaluate the statements / functions.
Post-decrement k First use the current value of k to valuate current
statements / functions then decrease k by unity.

The following program illustrates the increment and decrement operators.

PROGRAM 4.7 Illustrates increment and decrement operators.

#include <iostream>
using namespace std;
int main()

{int a = 6, p = 4,r=3,n =5,A,B,C,K ;

A = 6*++n ;
cout << A = <<A <<\t n = <<n <<endl;
K = 5*a ;
cout<<K = <<K<<\t a = <<a << endl;

B =r++*r++ ;
cout<< B = <<B<<\t r = << r << endl;
C = p *p ;
cout<<C= << C<<\t p= << p << endl;
return 0;
}

The expected output given below is self explanatory. However, it is also explained.
A = 36 n = 6
K = 30 a = 5
B = 9 r = 5
C= 16 p= 2
88 Programming with C++

For the first line of output n = 5. The n is first incremented to 6 and then multiplied by 6
to give 36. The second line of output is obtained by multiplication of 5 with the initial value
of a, which is 6. The variable a is then decremented to 5. The third line is obtained by
multiplying r with r, taking the initial value. Then r is incremented twice. The last line of output
is obtained similarly. The program below illustrates more such cases.

PROGRAM 4.8 Illustrates application of increment and decrement operators.

#include <iostream>
using namespace std;
int main()
{int m=6,n=2,p=4,r=3,s=8,k = 4,a,b,c,d ;
a =++n+ ++m;
b = s++ * s++;
c = p *p ;
d = ( k* k)*++r ;
cout<<a = <<a<<,\tn = <<n<<,\tm = <<m<<endl;
cout<<b = <<b <<,\ts = <<s<<\n;
cout<<c = <<c<<,\tp = <<p<<endl;
cout<<d = <<d <<,\tk = <<k<<,\tr = <<r<<endl;
return 0;
}

The expected output is given below.


a = 10, n = 3, m = 7
b = 64, s = 10
c = 16, p = 2
d = 16, k = 2, r = 4
In the first line of output a = (2 + 1) + (6 + 1) = 10. For the second line of output s is
increased after the multiplication, so b = 8 8 = 64. But s has got increment twice, so its value
becomes 10. Similarly in the third line of output the decrement in the value of p happens after
the multiplication, therefore value of c = 16 and p has got decrement twice, so its value has
decreased from 4 to 2. For the fourth line of output the value of k is pre-decreased twice because
the decrement operator has higher precedence than the operator *. Similarly value of r is increased
from 3 to 4 then multiplied with the first factor which is 4. So the result is 16.
As you have seen in the above program, in a complex expression wherein a variable appears
several times, it would be better not to use increment or decrement operators because it becomes
difficult for the programmer to keep track of changes in values. In the following program for
the expression E = ++a* a*++a; you would expect for a = 6, the E = 7 6 7, but it is equal
to 6 6 7. Because value of a is first increased to 7 and then decreased to 6 before the first
multiplication. It is then increased to 7 and multiplied to 36.
Similar cases can arise in expressions like ++m* m. If initial value of m is 4 you would
expect the expression to evaluate to (4 + 1)(5 1) = 20 but program gives a value 16. Because
the value of m is first increased then it is followed by decrement and then multiplication. So
the expression evaluates as 4 4 = 16. Thus if we have an expression like
Operators 89

A = ++n * n ;
The result is A = n*n ; with the initial value of n, because ++ and have higher precedence
than *. But if you have an expression like
A = ++n * p* n;
It would evaluate as A = (n+1) *(p1)*(n1);
The following program involves product of three factors like the example given above, and
it is interesting to note the results. Would you like to explain the results?

PROGRAM 4.9 Illustrates use of operator ++ and in along with other operators.

#include <iostream>
using namespace std;
int main()
{
int a = 6, n= 5,s =8, p=4,r=3,A,B,C,K,M,D,E ;
A = ++n* p * n ; // Equivalent to 6*3*5=90 and now p = 3
cout << n = <<n <<, A = <<A <<endl;
B = ++a*2* a; // This is equivalent to 7*2*6
D = a * ++a ; // This is equivalent to 6*6
E = ++a* a*++a; // Equivalent to 6*6*7 = 252
cout<<B = <<B<<, a = <<a << , D = <<D <<, E = << E
<<endl;

M = ++s* s; // equivalent to 8*8

K =++r +4 r ; // Equivalent to 4+4-3=5


cout<< K = <<K<<, r = << r <<, M = <<M<< endl;
C =p++* 5*p; // Equivalent to p *5 *p and p =3
// See calculation for A above
cout<<C= << C<<, p = << p << endl;
return 0;
}
The expected output is given below.
n = 5, A = 90
B = 84, a = 7, D = 36, E = 252
K = 5, r = 3, M = 64
C= 45, p = 3

4.6 RELATIONAL OPERATORS

These operators are used to compare two variables and are generally used with conditional
statements. For example, the code if(A==B) means if A and B are equal. Note that in this two
equal to signs (==) are used. Programmers often make a mistake by using single =. The other
relational operators are explained in Table 4.1. These are explained as well as their applications
are illustrated in Chapter 5.
90 Programming with C++

4.7 BOOLEAN OPERATORS

Boolean operators are logical operators. They relate the logical statements. Let A and B be the
two variable representing two logical statements. The logical variable have only two states that
is either it is true or false. If it is true the variable has a value 1 or a positive value. If it is false it
has value zero. The three Boolean operators are OR, AND and NOT. Table 4.5 gives details
about these operators and their symbols.
Table 4.5 Boolean Operators

Condition Operator Description


(i) A OR B || If either A or B or both are true then A|| B =1
It is false only when both A and B are false. In that
case A||B = 0
(ii) A AND B && If both A and B are true then A && B = 1 else
A&&B =0
(It is false when any one is false)
(iii) NOT A ! True if A evaluates to be false, i.e.
If A is false then !A = 1
and false when A evaluates true, i.e.
If A is true then !A = 0

The evaluation of various conditions in terms of true or false in different situations are given
in Table 4.6(a,b,c) below.

Table 4.6 (a), (b) and (c)

(a) A OR B (b) A AND B (c) NOT A


A B A||B A B A&&B A !A
false false false false false false true false
true false true true false false false true
false true true false true false
true true true true true true

The program below illustrates the applications of Boolean operators.

PROGRAM 4.10 Illustrates the application of Boolean operators.

#include <iostream>
using namespace std;
int main()
{ int p, q, r, s,t,x, y, z;
p =1;
Operators 91

q = 0;
r = 1;

s = p||q;
t = !q;
x = p&&q;
y = (p || q && r||s);
z = (!p || !q && !r || s);

cout << s = <<s << , t = << t <<, x = <<x<< endl;


cout << y = <<y <<, z = <<z<< endl;
return 0; }

The expected output given below should be verified by reader by calculations with help of Table
4.7(a,b,c).
s = 1, t = 1, x = 0
y = 1, z = 1

4.8 BITWISE OPERATORS

As already discussed in Chapter 1, a bit is the basic unit of memory. It can have only two states.
If it is set its value is 1 otherwise it is zero. Bitwise operation means convert the number into
binary and the carry out the operation on each bit individually. For example let us take the
operation complement represented by symbol (~). Let us take a number
short A = 42;
A short number is stored in two byte or 16 bits. Therefore,
A when expressed in binary = 00000000 00101010
Complement of A is ~A = 11111111 11010101
The compliment operator changes the bit with value 0 to 1 and the one with value 1 is
changed to 0. The different bitwise operators are listed in Table 4.7 below. It also illustrates
codes.
Table 4 .7 Bitwise operators

Operator Description Example of code


& AND A&B ;
| OR A|B;
^ XOR A^B ;
>> Shift right A >>2;//shift right by 2 places
<< Shift left A<<2;
~ Complement ~A;
&= Bitwise AND assign A &= B;

Contd...
92 Programming with C++

|= Bitwise OR assign A |= B;
^= Bitwise XOR assign A ^= B;
<<= Bitwise shift left assign A <<= 2;
Shift left by 2 places and assign to A
>>= Bitwise shift right assign A >>= 1;
Shift right by 1 place and assign to A

The operators AND, OR and XOR are explained in truth Table 4.8 below.
Table 4.8 Bitwise operators AND, OR and XOR

Bit1= A Bit2 = B A&B A|B A^B


0 0 0 0 0
1 0 0 1 1
0 1 0 1 1
1 1 1 1 0

The programs given below explain the application of some of these operators.

PROGRAM 4.11 Operator complement (~) is used to determine the maximum value of
an integer that can be stored on my PC.

#include<iostream>
using namespace std;

void main()
{ unsigned A = 0;
A = ~ A;
cout << A = <<A <<endl;
}

The expected output is given below.


A = 4294967295
The following program illustrates the application of bitwise AND operator (&).

PROGRAM 4.12 Illustrates bitwise AND operator.

#include<iostream>
using namespace std;

void main()
{ short A =24;
Operators 93
short B = 8;
int C = A&B;
cout << C = <<C <<endl;
}
The expected output is given below.
C = 8
The output is explained as below. A short number is stored in two bytes, therefore,
24 in binary is equal to 00000000 00011000
8 in binary is equal to 00000000 00001000
Bitwise AND is equal to 00000000 00001000
The result 0000000000001000 in binary is equal to 8.
The following program illustrates OR and left shift operators.

PROGRAM 4.13 Illustrates the operators OR and left shift (<<).

#include<iostream>
using namespace std;
void main()
{ short A =42;
short B = 12;
int C = A|B;
int D = A<<1;

cout << C = <<C <<endl;


cout<< D = <<D <<endl;
}

The expected output is as under.


C = 46
D = 84
Explanation of output is given below. A short number is stored in two bytes or 16 bits.
Therefore,
42 in binary is equal to 00000000 00101010
12 in binary is equal to 00000000 00001100
Bitwise OR operation results in 00000000 00101110
This is equal to 46 in decimal
For the variable D, the digits of A are shifted left by 1 place and assigned to D. So the original
binary number 00000000 00101010 now becomes 00000000 01010100 which is equal to 84,
i.e. the number gets multiplied by 2. Thus shifting a digit to left means multiplication by two.
94 Programming with C++

PROGRAM 4.14 Illustrates the operators ^ , >>= and <<= .

#include<iostream>
using namespace std;

void main()
{short A =42;

short B = 12;
short C = 24;
short D = A^B; // XOR operator
C <<= 1;
A <<=2; // Shift to left by 2 places and assign
B >>=2 ; // shift right by 2 places and assign
cout<< A = <<A<< \tB = << B <<endl;
cout << C = <<C <<endl;
cout << D = << D <<endl;
}

The expected output is given below.


A = 168 B = 3
C = 48
D = 38

The binary equivalent of A = 42 has been shifted two places to left. So the number gets
multiplied by 4. So A = 168. Similarly the right shift by two places in case of B divides it by
4.The binary equivalent of 24 has been shifted to left by one place and assigned to C. Therefore,
C = 242 = 48. For A ^ B see the following explanation.
Binary equivalent of 42 is 00000000 00101010
Binary equivalent of 12 00000000 00001100
Bitwise XOR operation gives 00000000 00100110
This is equivalent to 38.
The following Program illustrates more of the compound assignment operators.

PROGRAM 4.15 Illustrates the application of operators ^=, &= and |=.

#include<iostream>
using namespace std;
void main()
{ short A =20, D , E, F;
short B = 18;
short C = 30;
D = C^=B;
E = A &=B ;
F = C|=A ;
Operators 95
cout <<E = <<E <<endl;
cout <<F = << F <<endl;
cout << D = <<D <<endl;
}

The expected output is given below. Try to explain the output.


E = 16
F = 28
D = 12

Chapter 18 deals exclusively with operations on bit sets based on functions in <bitset> header
file.

4.9 PRECEDENCE OF OPERATORS

Precedence is an important aspect of operators. A partial list of operators and their precedence
is given in Table 4.9. The table does not include all the operators because we have not so far dealt
with them. For a more detailed list see Appendix C.
Table 4.9 A partial precedence table. Those higher in list have higher precedence

Operator Type Associativity


() Parentheses Left to right
[] Array subcript Left to right
++ Unary postfix Left to right
++ Unary prefix Left to right
+ Unary plus, unary minus Right to left
* / % Multiplicative Left to right
+ Additive Left to right
<< Bitwise left shift Left to right
>> Bitwise right shift Left to right
<, <=, > , >= Relational operators Left to right
== , != Relational Left to right
& Bitwise AND Left to right
^ Bitwise XOR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
= , *= , /= , %=, + =, = Assignment operators Right to left
&=, ^=, |=, <<=, >>= Right to left
Comma Evaluate Left to right

You might also like