Operators in C++: Show Examples Operato R Description Example
Operators in C++: Show Examples Operato R Description Example
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provides the following types of
operators:
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
Arithmetic Operators:
There are following arithmetic operators supported by C++ language:
Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operato
r
Description
Example
A + B will give 30
B / A will give 2
B % A will give 0
++
--
Relational Operators:
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then:
Show Examples
Operato
r
Description
Example
==
(A == B) is not true.
!=
(A != B) is true.
>
<
(A < B) is true.
>=
<=
(A <= B) is true.
Logical Operators:
There are following logical operators supported by C++ language
Assume variable A holds 1 and variable B holds 0, then:
Show Examples
Operato
r
Description
Example
&&
(A && B) is false.
||
(A || B) is true.
Bitwise Operators:
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows:
p
p&q
p|q
p^q
Assume if A = 60; and B = 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
----------------A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:
Show Examples
Operato
r
Description
Example
&
binary number.
<<
>>
Assignment Operators:
There are following assignment operators supported by C++ language:
Show Examples
Operato
r
Description
Example
+=
C += A is equivalent to C = C + A
-=
C -= A is equivalent to C = C - A
*=
C *= A is equivalent to C = C * A
/=
C /= A is equivalent to C = C / A
operand
%=
C %= A is equivalent to C = C % A
<<=
>>=
&=
^=
C ^= 2 is same as C = C ^ 2
|=
C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by C++ Language.
Operator
Description
sizeof
Condition ? X : Y
Cast
&
Operator
Associativity
Postfix
() [] -> . ++ - -
Left to right
Unary
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
<< >>
Left to right
Relational
Left to right
Equality
== !=
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
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right