Operators in C++ – Part 2

Written by

Vaaruni Agarwal

In the previous chapter, we looked upon the Arithmetic, Assignment and Relational Operators.

Now we will take a look at the Logical, Bitwise and Miscellaneous Operators, in this chapter.

Logical Operators:

Following logical operators are supported by C++ language. Here we have assumed that A holds 1 while B holds 0.

Operator  Description  Example 
&&  AND Operator, returns true if both the operands are non zero A && B will give False 
||  OR Operator, returns true if either of the operands are non zero A || B will give True 
NOT Operator, negates the value of the operand !A  will give False

!B will give True 


Bitwise Operators:

Bitwise Operators work on bit level and perform operations on a bit by bit basis, now if we assume A = 60 and B = 13, then the binary representation of these are as follows:

A= 00111100


Now, the Bitwise Operators in C++ will produce the following results as shown:

Operator  Description  Example 
Binary AND, copies a bit if it is in both operands  (A & B) will give 12 i.e. 00001100 
Binary OR, copies a bit if it is in either operand (A | B) will give 61 i.e. 00111101
Binary XOR, copies a bit if it is set in one operand (A ^ B) will give 49 i.e. 00110001 
Binary Ones, complements the bits  ~A will give -61 i.e. 11000011 in 2’s complement due to signed binary number 
<<  Binary left shift operator, the left operand’s value is moved left by the number of bits specified A<<2 will give 240 i.e. 11110000
>> Binary right shift operator, the left operand’s value is moved right by the number of bits specified.  A>>2 will give 15 i.e. 00001111


Miscellaneous Operators:

There are some Miscellaneous Operators offered by the C++, these are as follows.

Here, A and B are two integer variables with values 20 and 10 respectively.

Operator  Description  Example 
sizeof  Returns the size of the specified variable  sizeof(A) will return 4 
Cond?X:Y Conditional Operator, returns X if the condition is true and Y if it is false A>B?A:B will return A
, Comma Operator, is used to separate variables, expressions, etc. int A,B; 



The Conditional Operator is the only ternary operator in C++ as it requires three operands to act upon. 

This operator also acts as a substitute for the if-else statements. We will learn about them later on.

Operators in C++ &#8211; Part 2