C++ Operators with Examples

What are Operators?

An operator is a symbol used for performing operations on operands. An operator operates operands. The operations can be mathematical or logical. There are different types of operators in C++ for performing different operations.

Consider the following operation:

a = x + y;

In the above statement, x and y are the operands while + is an addition operator. When the C++ compiler encounters the above statement, it will add x and y and store the result in variable a.

In this C++ Tutorial, you will Learn:

Arithmetic Operators

They are the types of operators used for performing mathematical/arithmetic operations. They include:

Operator Description
+ addition operator Adds to operands.
– subtraction operator Subtracts 2nd operand from 1st operand.
* multiplication operator Multiplies 2 operands.
/ division operator. Divides numerator by denominator.
% modulus operator Returns remainder after division.
++ increment operator Increases an integer value by 1.
— decrement operator. Decreases an integer value by 1.

For example:

#include <iostream>
using namespace std;
int main() {
	int a = 11;
	int b = 5;
	int c;

	cout << "a + b is :" << a+b << endl; //11+5

	cout << "a - b is :" << a-b << endl; //11-5

	cout << "a * b is :" << a*b << endl; //11*5

	cout << "a / b is :" << a/b << endl; //11/5

	cout << "a % b is :" << a%b << endl; //11%5

	cout << "a++ is :" << a++ << endl; //11++

	cout << "a-- is :" << a-- << endl; //12--

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Declaring an integer variable a and initializing it to 11.
  5. Declaring an integer variable b and initializing it to 5.
  6. Declaring an integer variable c.
  7. Printing value of operation a+b alongside other text on the console.
  8. Printing value of operation a-b alongside other text on the console.
  9. Printing value of operation a*b alongside other text on the console.
  10. Printing value of operation a/b alongside other text on the console.
  11. Printing value of operation a%b alongside other text on the console.
  12. Printing value of operation a++ alongside other text on the console.
  13. Printing value of operation a– alongside other text on the console.
  14. The main() function should return an value if the program runs fine.
  15. End of the body of the main() function.

Relational Operators

These types of operators perform comparisons on operands. For example, you may need to know which operand is greater than the other, or less than the other. They include:

Description

Operator Description
== equal to operator. Checks equality of two operand values.
!= not equal to operator Checks equality of two operand values.
> great than operator Checks whether value of left operand is greater than value of right operand.
< less than operator. Checks whether value of left operand is less than value of right operand.
>= greater than or equal to operator Checks whether value of left operand is greater than or equal to value of right operand.
<= less than or equal to operator. Checks whether value of left operand is less than or equal to value of right operand.

For example:

#include <iostream>
using namespace std;

int main() {
	int a = 11;
	int b = 5;

	cout << "a=11, b=5" << endl;
	if (a == b) {
		cout << "a == b is true" << endl;
	}
	else {
		cout << " a == b is false" << endl;
	}

	if (a < b) {
		cout << "a < b is true" << endl;
	}
	else {
		cout << "a < b is false" << endl;
	}

	if (a > b) {
		cout << "a > b is true" << endl;
	}
	else {
		cout << "a > b is false" << endl;
	}

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Declaring an integer variable a and initializing it to 11.
  5. Declaring an integer variable b and initializing it to 5.
  6. Printing some text on the console stating the values of variables a and b.
  7. Performing the arithmetic operation, a==b in an if decision making statement to know whether it’s true or false. The { marks the beginning of the body of the if statement.
  8. Text to print on the console if the operation a==b is true. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the if statement.
  9. The else part of the above if statement. It states what to do if the operation a==b is false.
  10. Text to print on the console if the operation a==b is false. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the else statement.
  11. Performing the arithmetic operation, a<b in an if decision making statement to know whether it’s true or false. The { marks the beginning of the body of the if statement.
  12. Text to print on the console if the operation a<b is true. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the if statement.
  13. The else part of the above if statement. It states what to do if the operation a<b is false.
  14. Text to print on the console if the operation a<b is false. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the else statement.
  15. Performing the arithmetic operation a>b in an if decision making statement to know whether it’s true or false. The { marks the beginning of the body of the if statement.
  16. Text to print on the console if the operation a>b is true. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the if statement.
  17. The else part of the above if statement. It states what to do if the operation a>b is false.
  18. Text to print on the console if the operation a>b is false. The endl is a C++ keyword for end line. It pushes the cursor to start printing in the next line. The } marks the end of the body of the else statement.
  19. The main() function should return an value if the program runs fine.
  20. End of the body of the main() function.

Logical Operators

The logical operators combine two/more constraints/conditions. Logical operators also complement evaluation of original condition under consideration. They include:

Operator Description
&& logical AND operator. The condition is true if both operands are not zero.
|| logical OR operator. The condition is true if one of the operands is non-zero.
! logical NOT operator. It reverses operand’s logical state. If the operand is true, the ! operator makes it false.

For example:

#include <iostream> 
using namespace std;
int main()
{
	int a = 5, b = 2, c = 6, d = 4;
	if (a == b && c > d)
		cout << "a equals to b AND c is greater than d\n";
	else
		cout << "AND operation returned false\n";

	if (a == b || c > d)
		cout << "a equals to b OR c is greater than d\n";
	else
		cout << "Neither a is equal to b nor c is greater than d\n";

	if (!b)
		cout << "b is zero\n";
	else
		cout << "b is not zero";

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. The { marks start of body of the main() function.
  5. Declaring 4 integer variables a, b, c and d and assigning them different values.
  6. Using the && (AND) operator inside the if statement. It joins two conditions, value of a equals to value of b and, value of a is greater than value of b. First condition is false, second condition is true. False&&true is False, hence, the outcome of if is false.
  7. Text to print on console if the above if statement is true. This won’t be executed.
  8. Part to be executed if the above if statement is false.
  9. Text to print on the console if the if statement is false. This will be executed.
  10. Using the || (OR) operator within an if statement. It joins two conditions, value of a equals to value of b and, value of a is greater than value of b. First condition is false, second condition is true. False||true is True, hence, the outcome of if is true.
  11. Text to print on console if the above if statement is true. This will be executed.
  12. Part to be executed if the above if statement is false.
  13. Text to print on the console if the if statement is false. This will not be executed.
  14. Checking whether value of variable is 0.
  15. Text to print on console if the above if statement is true. This will not be executed.
  16. Part to be executed if the above if statement is false.
  17. Text to print on the console if the if statement is false. This will be executed.
  18. The main() function should return an value if the program runs fine.
  19. End of the body of the main() function.

Bitwise Operators

Bitwise operators perform bit-level operations on operands. First, operators are converted to bit level then operations are performed on the operands. When arithmetic operations like addition and subtraction are done at bit level, results can be achieved faster. They include:

Operator Description
& (bitwise AND). It takes 2 numbers (operands) then performs AND on each bit of two numbers. If both are 1, AND returns 1, otherwise 0.
| (bitwise OR) Takes 2 numbers (operands) then performs OR on every bit of two numbers. It returns 1 if one of the bits is 1.
^ (the bitwise XOR) Takes 2 numbers (operands) then performs XOR on every bit of 2 numbers. It returns 1 if both bits are different.
<< (left shift) Takes two numbers then left shifts the bits of the first operand. The second operand determines total places to shift.
>> (right shift) Takes two numbers then right shifts the bits of the first operand. The second operand determines number of places to shift.
~ (bitwise NOT). Takes number then inverts all its bits.
#include <iostream>
using namespace std;

int main() {
	unsigned int p = 60;	  // 60 = 0011 1100  
	unsigned int q = 13;	  // 13 = 0000 1101
	int z = 0;

	z = p & q;
	cout << "p&q is : " << z << endl; // 12 = 0000 1100

	z = p | q;
	cout << "p|q is : " << z << endl; // 61 = 0011 1101

	z = p ^ q;
	cout << "p^q is : " << z << endl; // 49 = 0011 0001

	z = ~p;
	cout << "~p is : " << z << endl; // -61 = 1100 0011

	z = p << 2;
	cout << "p<<2 is: " << z << endl; // 240 = 1111 0000

	z = p >> 2;
	cout << "p>>2 is : " << z << endl; // 15 = 0000 1111

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Declaring an unsigned integer variables p and assigning it a value of 60, which is, 0011 1100 in binary.
  5. Declaring an unsigned integer variables q and assigning it a value of 13, which is, 0000 1101 in binary.
  6. Declaring an integer variable z and initializing it to 0.
  7. Performing the bitwise & (AND) operation on variables p and q and storing the result in variable z.
  8. Printing the result of the above operation on the console alongside other text.
  9. Performing the bitwise | (OR) operation on variables p and q and storing the result in variable z.
  10. Printing the result of the above operation on the console alongside other text.
  11. Performing the bitwise ^ (XOR) operation on variables p and q and storing the result in variable z.
  12. Printing the result of the above operation on the console alongside other text.
  13. Performing the bitwise ~ (NOT) operation on variables p and q and storing the result in variable z.
  14. Printing the result of the above operation on the console alongside other text.
  15. Performing the left shift operation on variable p and storing the result in variable z.
  16. Printing the result of the above operation on the console alongside other text.
  17. Performing the right shift operation on variable p and storing the result in variable z.
  18. Printing the result of the above operation on the console alongside other text.
  19. The main() function should return an value if the program runs fine.
  20. End of the body of the main() function.

Assignment Operators

Assignment operators assign values to variables. The operand/variable is added to left side of the operator while the value is added to the right side of the operator. The variable and the value must belong to the same data type, otherwise, the C++ compiler will raise error. For example:

x = 5;

In the above example, x is the variable/operand, = is the assignment operator while 5 is the value. Here are the popular assignment operators in C++:

Operator Description
= (simple assignment operator) It assigns value on the right to variable on the left.
+= (Add AND assignment operator) It first adds value of left operand to value of right operand then assigns result to variable on the left.
-= (Subtract AND assignment operator) It first subtracts value of right operand from value of left operand then assigns result to variable on the left.
*= (Multiply AND assignment operator) It first multiplies value of left operand with value of right operand then assigns result to variable on the left.
/= (Division AND assignment operator) It first divides value of left operand by value of right operand then assigns result to variable on the left.

For example:

#include <iostream> 
using namespace std;
int main()
{
	int x = 5;
	cout << "Initial value of x is " << x << "\n";

	x += 5;
	cout << "x += 5 gives :" << x << "\n";

	x -= 5;
	cout << "x -= 5 gives : " << x << "\n";

	x *= 5;
	cout << "x *= 5 gives :" << x << "\n";

	x /= 5;
	cout << "x /= 5 gives : " << x << "\n";

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added.
  4. The { marks start of body of the main() function.
  5. Declaring an integer variables x and assigning it a value of 5.
  6. Printing value of variable x alongside other text on the console. The \n is a new line character. It moves the cursor to the next line when printing.
  7. Adding 5 to value of variable x and assigning result to variable x.
  8. Printing value of variable x on the console alongside other text.
  9. Subtracting 5 from value of x and assigning result to variable x.
  10. Printing value of variable x on the console alongside other text.
  11. Multiplying value of variable x with 5 and assigning result to variable x.
  12. Printing value of variable x on the console alongside other text.
  13. Dividing value of variable x by 5 and assigning result to variable x.
  14. Printing value of variable x on the console alongside other text.
  15. The main() function should return an value if the program runs fine.
  16. End of the body of the main() function.

Misc operator

Let us discuss other operators supported by C++:

sizeof operator

This operator determines a variable’s size. Use sizeof operator to determine the size of a data type. For example:

#include <iostream> 
using namespace std;
int main() {
	cout<<"Size of int : "<< sizeof(int) << "\n";

	cout<<"Size of char : " << sizeof(char) << "\n";

	cout<<"Size of float : " << sizeof(float) << "\n";

	cout<<"Size of double : " << sizeof(double) << "\n";

	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Determining the size of integer data type using sizeof operator and printing it alongside other text on the console.
  5. Determining the size of character data type using sizeof operator and printing it alongside other text on the console.
  6. Determining the size of float data type using sizeof operator and printing it alongside other text on the console.
  7. Determining the size of float data type using sizeof operator and printing it alongside other text on the console.
  8. The main() function should return an value if the program runs fine.
  9. End of the body of the main() function.

Comma Operator

The comma operator (,) triggers the performance of a sequence of operations. It expresses first operand and discards the result. Next, it evaluates the second operand and returns the value and type.

#include <iostream>
using namespace std;
int main() {
	int x, y;
	y = 100;
	x = (y++, y + 10, 99 + y);
	cout << x;
	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Declaring two integer variables x and y.
  5. Assigning the variable y a value of 100.
  6. Incrementing value of y and assigning result to variable x. It start with y at 100, then increments it to 101 (y++). Next, y is added to 10. Finally, y, still at 101, is added to 99, giving 200. x is now 200.
  7. Printing value of variable x on the console.
  8. The main() function should return an value if the program runs fine.
  9. End of the body of the main() function.

Conditional Operator

This operator evaluates a condition and acts based on the outcome of the evaluation.

Syntax:

Condition ? Expression2 : Expression3;

Parameters:

  • The Condition is the condition that is to be evaluated.
  • Expression1 is the expression to be executed if condition is true.
  • Expression3 is the expression to be executed if condition is false.

For example:

#include <iostream>
using namespace std;
int main() {
	int a = 1, b;
	b = (a < 10) ? 2 : 5;
	cout << "value of b: " << b << endl;
	return 0;
}

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Including the iostream header file in our code. It will allow us to read from and write to the console.
  2. Including the std namespace so as to use its classes and functions without calling it.
  3. Calling the main() function inside which the logic of the program should be added. The { marks start of body of the main() function.
  4. Declaring two integer variables a and b. Variable a has been assigned a value of 1.
  5. Assigning value to variable b. If variable a is less than 10, b will be assigned the value 2, otherwise, b will be assigned a value of 5.
  6. Printing value of variable b on the console alongside other text.
  7. The main() function should return an value if the program runs fine.
  8. End of the body of the main() function.

Operators Precedence

A single operation may have more than one operator. In that case, operator precedence determines the one evaluated first.

The following list shows the precedence of operators in C++, with decreasing precedence from left to right:

(), [],*, /, %, +/-, << , >>, == , !=, ^, |, &&, ||, ?:, =, +=, -=, *=, /=

Summary:

  • Operators are symbols for performing logical and arithmetic operations.
  • Arithmetic operators help us perform various arithmetic operations on operands.
  • Relational operators help us perform various comparison operations on operands.
  • Logical operators help us perform various logical operations on operands.
  • Bitwise operators help us perform bitwise operations on operands.
  • Assignment operators help us perform various arithmetic operations on operands.
  • The sizeof operator returns the size of a variable or data type.
  • The comma operator executes a sequence of operations.
  • The conditional operator evaluates a condition and acts based on the outcome.