Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

C++ Operator

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

C++ is a versatile programming language that forms the backbone of many software applications. In order to write effective C++ code, operators play a very crucial part. These are special symbols that tell the compiler to perform specific mathematical or logical manipulations. 

CPP Operator

This article will simplify the concept of operators in C++. We'll explore different types of operators, such as arithmetic, relational, and logical operators, among others. After reading this article, you will have a better understanding of how and where different operators should be used.

Arithmetic Operators

In C++, arithmetic operators are the most basic tools you have for handling numbers. Think of them as the basic operations you would do on a calculator: addition, subtraction, multiplication, division, and finding the remainder. These operators help you perform calculations and manipulate data in your programs.

Addition (+)

The + operator adds two numbers together. For example, if you have int a = 5; int b = 3;, then a + b would give you 8.

Subtraction (-)

The - operator subtracts one number from another. Using the same numbers, a - b would give you 2.

Multiplication (*)

The * operator multiplies two numbers. So, a * b would result in 15.

Division (/)

The / operator divides one number by another. It's important to remember that if you're working with integers, C++ will give you an integer result, truncating any decimal. For a and b, a / b would give you 1, not 1.666....

Modulus (%)

The % operator, also known as the modulus operator, gives you the remainder of a division. For example, a % b would give you 2, because when 5 is divided by 3, the remainder is 2.

Here's a simple example of these operators in action:

  • C

C

#include <iostream>
using namespace std;

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

cout << "Addition: " << a + b << endl; // Output: Addition: 8
cout << "Subtraction: " << a - b << endl; // Output: Subtraction: 2
cout << "Multiplication: " << a * b << endl; // Output: Multiplication: 15
cout << "Division: " << a / b << endl; // Output: Division: 1
cout << "Modulus: " << a % b << endl; // Output: Modulus: 2

return 0;
}

Output

Addition: 8
Subtraction: 2
Multiplication: 15
Division: 1
Modulus: 2


This code snippet defines two integer variables, a and b, and then uses arithmetic operators to perform different calculations. The results are printed to the console, demonstrating how each operator functions.

Understanding these operators is fundamental for any programming task in C++, from simple calculations to complex algorithms. They are the building blocks that allow you to manipulate data and implement logic in your programs.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Relational Operators

While writing C++ programs, it's often necessary to compare values to make decisions. This is where relational operators come into play. They help you check how two values relate to each other, such as whether one is greater than the other, or if two values are equal.

Equal to (==)

The == operator checks if two values are equal. If int a = 5; int b = 5;, then a == b would be true because both a and b are 5.

Not equal to (!=)

The != operator checks if two values are not equal. Using the same variables, if b was changed to 3, then a != b would be true because 5 is not equal to 3.

Greater than (>)

The > operator checks if the value on the left is greater than the value on the right. So, a > b would be true if a is 5 and b is 3.

Less than (<)

The < operator checks if the value on the left is less than the value on the right. If a was 2 and b was 3, then a < b would be true.

Greater than or equal to (>=)

The >= operator checks if the left value is greater than or equal to the right value. If a is 5, a >= b would be true for b being 3 or 5.

Less than or equal to (<=)

The <= operator checks if the left value is less than or equal to the right value. If a is 3, a <= b would be true for b being 3 or 5.

Here's a code example demonstrating these operators:

  • C

C

#include <iostream>
using namespace std;

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

cout << "Equal to: " << (a == b) << endl; // Output: Equal to: 0 (false)
cout << "Not equal to: " << (a != b) << endl; // Output: Not equal to: 1 (true)
cout << "Greater than: " << (a > b) << endl; // Output: Greater than: 1 (true)
cout << "Less than: " << (a < b) << endl; // Output: Less than: 0 (false)
cout << "Greater than or equal to: " << (a >= b) << endl; // Output: Greater than or equal to: 1 (true)
cout << "Less than or equal to: " << (a <= b) << endl; // Output: Less than or equal to: 0 (false)

return 0;
}

Output


Equal to: 0
Not equal to: 1
Greater than: 1
Less than: 0
Greater than or equal to: 1
Less than or equal to: 0


This code snippet demonstrates how each relational operator is used to compare two integers, a and b. The results are printed to the console, showing which comparisons are true (1) and which are false (0).

Relational operators are crucial for controlling the flow of programs, allowing decisions to be made based on the comparison of values. Whether you're checking if a user's input matches a specific condition or sorting a list of numbers, understanding and using these operators is key.

Logical Operators

Logical operators in C++ are used to combine or invert conditions. They are essential when you need to make decisions based on multiple conditions. There are three main logical operators: AND, OR, and NOT.

AND (&&)

The && operator returns true only if both conditions on either side are true. For example, if bool condition1 = true; bool condition2 = false;, then condition1 && condition2 would be false because both conditions are not true.

OR (||)

The || operator returns true if at least one of the conditions on either side is true. Using the same variables, condition1 || condition2 would be true because at least one condition (condition1) is true.

NOT (!)

The ! operator inverts the truth value of a condition. So, if condition1 is true, !condition1 would be false.

Here's how you can use these operators in a C++ program:

  • C++

C++

#include <iostream>
using namespace std;

int main() {
bool condition1 = true;
bool condition2 = false;

cout << "AND (both true): " << (condition1 && condition1) << endl; // Output: AND (both true): 1 (true)
cout << "AND (one false): " << (condition1 && condition2) << endl; // Output: AND (one false): 0 (false)
cout << "OR (one true): " << (condition1 || condition2) << endl; // Output: OR (one true): 1 (true)
cout << "OR (both false): " << (condition2 || condition2) << endl; // Output: OR (both false): 0 (false)
cout << "NOT (invert true): " << (!condition1) << endl; // Output: NOT (invert true): 0 (false)
cout << "NOT (invert false): " << (!condition2) << endl; // Output: NOT (invert false): 1 (true)

return 0;
}

Output

AND (both true): 1
AND (one false): 0
OR (one true): 1
OR (both false): 0
NOT (invert true): 0
NOT (invert false): 1


This code defines two boolean variables, condition1 and condition2, and demonstrates each logical operator's effect. For the AND operator, both conditions must be true for the result to be true. For the OR operator, only one of the conditions needs to be true. The NOT operator simply inverts the truth value of a condition.

Logical operators are particularly useful in if statements and loops, where you might need to check multiple conditions before deciding which block of code to execute. They help in building complex logical conditions in a readable and efficient way.

Bitwise Operators

Bitwise operators in C++ work at the bit level, which is the most basic form of data in computing, represented by 0s and 1s. These operators can perform operations on individual bits of integer data types. Understanding bitwise operators is crucial for low-level programming tasks such as device driver writing or software interfacing with hardware.

AND (&)

The & operator compares each bit of two numbers and returns a new number whose bits are set to 1 only if both corresponding bits in the original numbers are also 1. For example, if int a = 12; /* 1100 in binary */ int b = 5; /* 0101 in binary */, then a & b would result in 4 /* 0100 in binary */.

OR (|)

The | operator compares each bit of two numbers and returns a new number whose bits are set to 1 if either of the corresponding bits in the original numbers is 1. Using the same numbers, a | b would result in 13 /* 1101 in binary */.

XOR (^)

The ^ (exclusive OR) operator compares each bit of two numbers and returns a new number whose bits are set to 1 if the corresponding bits in the original numbers are different. In our example, a ^ b would give 9 /* 1001 in binary */.

NOT (~)

The ~ operator flips all the bits of its operand. If a is 12 (1100 in binary), then ~a will result in -13 in most C++ environments due to two's complement representation of negative numbers, where the binary representation is 11110011 (for an 8-bit system, as an example).

Left Shift (<<)

The << operator shifts the bits of its left-hand operand to the left by the number of positions specified by its right-hand operand. For a << 1, the result would be 24 /* 11000 in binary */, effectively multiplying a by 2.

Right Shift (>>)

The >> operator shifts the bits of its left-hand operand to the right by the number of positions specified by its right-hand operand. For a >> 1, the result would be 6 /* 0110 in binary */, effectively dividing a by 2.

Here's a simple code example demonstrating bitwise operators:

  • C++

C++

#include <iostream>
using namespace std;

int main() {
int a = 12; // 1100 in binary
int b = 5; // 0101 in binary

cout << "AND: " << (a & b) << endl; // Output: AND: 4
cout << "OR: " << (a | b) << endl; // Output: OR: 13
cout << "XOR: " << (a ^ b) << endl; // Output: XOR: 9
cout << "NOT: " << (~a) << endl; // Output: NOT: -13 (for 32-bit int, the actual binary representation will vary)
cout << "Left Shift: " << (a << 1) << endl; // Output: Left Shift: 24
cout << "Right Shift: " << (a >> 1) << endl; // Output: Right Shift: 6

return 0;
}

Output

AND: 4
OR: 13
XOR: 9
NOT: -13
Left Shift: 24
Right Shift: 6


This code snippet demonstrates the use of each bitwise operator with integers a and b. The results illustrate how these operators manipulate individual bits within these integers to produce new values.

Bitwise operators are powerful tools in C++, enabling direct manipulation of data at the bit level. They're essential for performance-critical applications, hardware programming, and situations requiring precise control over the binary representation of data.

Assignment Operators

Assignment operators in C++ are used to assign values to variables. The most common assignment operator is =, which you've probably used to set initial values for your variables. But C++ also offers a variety of other assignment operators that combine arithmetic or bitwise operations with assignment. These operators can make your code more concise and easier to read.

Simple Assignment (=)

The = operator assigns the value on its right to the variable on its left. For example, int a = 10; assigns the value 10 to the variable a.

Addition Assignment (+=)

The += operator adds the right operand to the left operand and assigns the result to the left operand. If a is 10, then a += 2; will result in a being 12.

Subtraction Assignment (-=)

The -= operator subtracts the right operand from the left operand and assigns the result to the left operand. Using a from above, a -= 2; would change a to 10 again.

Multiplication Assignment (*=)

The *= operator multiplies the left operand by the right operand and assigns the result to the left operand. If a is 10, then a *= 2; would make a 20.

Division Assignment (/=)

The /= operator divides the left operand by the right operand and assigns the result to the left operand. With a as 20, a /= 2; would change a back to 10.

Modulus Assignment (%=)

The %= operator takes the modulus using the two operands and assigns the result to the left operand. If a is 10, then a %= 3; would result in a being 1.

Bitwise AND Assignment (&=)

The &= operator performs a bitwise AND on both operands and assigns the result to the left operand. If int b = 12; // 1100 in binary, then b &= 5; // 0101 in binary would result in b being 4.

Bitwise OR Assignment (|=)

The |= operator performs a bitwise OR on both operands and assigns the result to the left operand. Using b from above, b |= 1; would change b to 5.

Bitwise XOR Assignment (^=)

The ^= operator performs a bitwise XOR on both operands and assigns the result to the left operand. If b is 5, then b ^= 2; would change b to 7.

Left Shift Assignment (<<=)

The <<= operator shifts the left operand to the left by the number of bits specified by the right operand and assigns the result to the left operand. For b = 5;, b <<= 1; would make b 10.

Right Shift Assignment (>>=)

The >>= operator shifts the left operand to the right by the number of bits specified by the right operand and assigns the result to the left operand. If b is 10, then b >>= 1; would change b back to 5.

Here's an example demonstrating these operators:

  • C++

C++

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 12;

a += 2; // a is now 12
a -= 2; // a is now 10
a *= 2; // a is now 20
a /= 2; // a is now 10
a %= 3; // a is now 1

b &= 5; // b is now 4
b |= 1; // b is now 5
b ^= 2; // b is now 7
b <<= 1; // b is now 14
b >>= 1; // b is now 7

cout << "a: " << a << ", b: " << b << endl;

return 0;
}

Output

a: 1, b: 7

 

This code snippet initializes two variables, a and b, and applies various assignment operators to them. The final values of a and b are printed to demonstrate the effect of each operator.

Assignment operators are a convenient way to perform an operation and assign the result to a variable in a single step. They simplify code and can make complex operations more readable.

Ternary or Conditional Operators

The ternary or conditional operator in C++ is a compact way to write an if-else statement that assigns a value to a variable based on a condition. It's called "ternary" because it takes three operands: a condition, a value to assign if the condition is true, and a value to assign if the condition is false.

The syntax for the ternary operator is: 

condition ? value_if_true : value_if_false;

Example Usage

Let's say you want to assign the larger of two numbers to a variable. You could use an if-else statement, but the ternary operator provides a more concise way to do it:

  • C++

C++

#include <iostream>
using namespace std;

int main() {
int a = 10;
int b = 20;

// Using ternary operator to assign the larger number to max
int max = (a > b) ? a : b;

cout << "The larger number is: " << max << endl; // Output: The larger number is: 20

return 0;
}

Output

The larger number is: 20

In this example, (a > b) is the condition. If it's true (i.e., if a is greater than b), max is assigned the value of a. If it's false, max is assigned the value of b. The ternary operator checks the condition and assigns the appropriate value to max in a single, neat line of code.

The ternary operator is especially useful for simple conditional assignments. It makes your code cleaner and easier to read by eliminating the need for multiple lines of if-else statements for straightforward conditions.

Note-: it's important to use the ternary operator cautiously. For complex conditions or assignments, a regular if-else statement might be more readable and easier to maintain.

Frequently Asked Questions

Can I use the ternary operator for more than just assignment operations?

Yes, the ternary operator can be used anywhere a value is needed, not just for assignments. However, it's most commonly used to assign a value to a variable conditionally. Be mindful of readability when using it in more complex expressions.

How does the modulus operator (%) behave with negative numbers?

The modulus operator (%) returns the remainder of a division operation. When used with negative numbers, the sign of the result is implementation-defined in C++, meaning it could be either positive or negative depending on the compiler. It's best to check your compiler's documentation for specifics.

Are bitwise operators only useful for low-level programming?

While bitwise operators are essential for low-level programming tasks, such as working with device drivers or direct hardware interaction, they also have applications in higher-level programming. They can be used for efficient data manipulation, setting flags, or even certain algorithms that benefit from direct bit manipulation.

Conclusion

In this article, we've explored the various types of operators in C++, starting with the basic arithmetic operators that allow us to perform mathematical operations. We then looked into relational operators for comparing values, logical operators for combining conditions, and bitwise operators for manipulating data at the bit level. We also discussed assignment operators, which are crucial for setting and updating variable values, and in the end we talked about ternary or conditional operator for concise conditional assignments.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Topics covered
1.
Introduction
2.
Arithmetic Operators
2.1.
Addition (+)
2.2.
Subtraction (-)
2.3.
Multiplication (*)
2.4.
Division (/)
2.5.
Modulus (%)
2.6.
C
3.
Relational Operators
3.1.
Equal to (==)
3.2.
Not equal to (!=)
3.3.
Greater than (>)
3.4.
Less than (<)
3.5.
Greater than or equal to (>=)
3.6.
Less than or equal to (<=)
3.7.
C
4.
Logical Operators
4.1.
AND (&&)
4.2.
OR (||)
4.3.
NOT (!)
4.4.
C++
5.
Bitwise Operators
5.1.
AND (&)
5.2.
OR (|)
5.3.
XOR (^)
5.4.
NOT (~)
5.5.
Left Shift (<<)
5.6.
Right Shift (>>)
5.7.
C++
6.
Assignment Operators
6.1.
Simple Assignment (=)
6.2.
Addition Assignment (+=)
6.3.
Subtraction Assignment (-=)
6.4.
Multiplication Assignment (*=)
6.5.
Division Assignment (/=)
6.6.
Modulus Assignment (%=)
6.7.
Bitwise AND Assignment (&=)
6.8.
Bitwise OR Assignment (|=)
6.9.
Bitwise XOR Assignment (^=)
6.10.
Left Shift Assignment (<<=)
6.11.
Right Shift Assignment (>>=)
6.12.
C++
7.
Ternary or Conditional Operators
7.1.
C++
8.
Frequently Asked Questions
8.1.
Can I use the ternary operator for more than just assignment operations?
8.2.
How does the modulus operator (%) behave with negative numbers?
8.3.
Are bitwise operators only useful for low-level programming?
9.
Conclusion