Operators in C++

Operator is a special symbol that tells the compiler to perform specific mathematical or logical Operation.

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Ternary or Conditional Operators
  • Shift Operators
  • Unary Operators
  • Comma Operator

operators in C++

Arithmetic Operators

Given table shows all the Arithmetic operator supported by C Language. Lets suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result
+ A+B 11
A-B 5
* A*B 24
/ A/B 2
% A%4 0

Relational Operators

Which can be used to check the Condition, it always return true or false. Lets suppose variable A hold 8 and B hold 3.

Operators Example (int A=8, B=3) Result
< A<B False
<= A<=10 True
> A>B True
>= A<=B False
== A== B False
!= A!=(-4) True

Logical Operator

Which can be used to combine more than one Condition?. Suppose you want to combined two conditions A<B and B>C, then you need to use Logical Operator like (A<B) && (B>C). Here && is Logical Operator.

Operator Example (int A=8, B=3, C=-10) Result
&& (A<B) && (B>C) False
|| (B!=-C) || (A==B) True
! !(B<=-A) True

Truth table of Logical Operator

C1 C2 C1 && C2 C1 || C2 !C1 !C2
T T T T F F
T F F T F T
F T F T T F
F F F F T T

Assignment operators

Which can be used to assign a value to a variable. Lets suppose variable A hold 8 and B hold 3.

Operator Example (int A=8, B=3) Result
+= A+=B or A=A+B 11
-= A-=3 or A=A+3 5
*= A*=7 or A=A*7 56
/= A/=B or A=A/B 2
%= A%=5 or A=A%5 3
=a=b Value of b will be assigned to a

Shift Operators

Shift Operators are used to shift Bits of any variable. It is of three types,

  1. Left Shift Operator <<
  2. Right Shift Operator >>
  3. Unsigned Right Shift Operator >>>

Bitwise Operators

There are used to change individual bits into a number. They work with only integral data types like charint and long and not with floating point values.

  • Bitwise AND operators &
  • Bitwise OR operator |
  • And bitwise XOR operator ^
  • And, bitwise NOT operator ~

They can be used as shorthand notation too, & = , |= , ^= , ~= etc.

Unary Operators

These are the operators which work on only one operand. There are many unary operators, but increment ++ and decrement -- operators are most used.

Other Unary Operators : address of &, dereference *new and delete, bitwise not ~, logical not !, unary minus - and unary plus +.


Ternary Operator

The ternary if-else ? : is an operator which has three operands.

int a = 10;
a > 5 ? cout << "true" : cout << "false"

Comma Operator

This is used to separate variable names and to separate expressions. In case of expressions, the value of last expression is produced and used.

Example :

int a,b,c; // variables declaration using comma operator
a=b++, c++; // a = c++ will be done.