Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
C++ is a versatile programming language that forms the backbone of many software applications. 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.
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.
Let's see the table of arithmetic operators with example:
Operator
Name
Description
Example
+
Addition
Adds two operands.
x + y
-
Subtraction
Subtracts the second operand from the first.
x - y
*
Multiplication
Multiplies two operands.
x * y
/
Division
Divides the first operand by the second. Returns the quotient.
x / y
%
Modulus
Divides the first operand by the second and returns the remainder.
x % y
++
Increment
Increments the operand by 1. Can be used as prefix (++x) or postfix (x++).
++x or x++
--
Decrement
Decrements the operand by 1. Can be used as prefix (--x) or postfix (x--).
--x or x--
+
Unary plus
Indicates a positive value. Has no effect on the operand.
+x
-
Unary minus
Negates the operand, changing its sign.
-x
+=
Addition
assignment Adds the right operand to the left operand and assigns the result to the left operand.
x += y (equivalent to x = x + y)
-=
Subtraction
assignment Subtracts the right operand from the left operand and assigns the result to the left operand.
x -= y (equivalent to x = x - y)
*=
Multiplication
assignment Multiplies the left operand by the right operand and assigns the result to the left operand.
x *= y (equivalent to x = x * y)
/=
Division
assignment Divides the left operand by the right operand and assigns the result (quotient) to the left operand.
x /= y (equivalent to x = x / y)
%=
Modulus
assignment Divides the left operand by the right operand and assigns the result (remainder) to the left operand.
x %= y (equivalent to x = x % y)
let's see a basic example of these operators:
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
This code 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.
Relational Operators
In C++, sometimes, we have to compare values to make decisions. This is where relational operators become useful. They help you check how two values relate to each other, like whether one is greater than the other, or if two values are equal.
Let's see a table of all the relational operators:
Operator
Name
Description
Example
==
Equal to
Checks if the values of two operands are equal. Returns true if they are equal, false otherwise.
x == y
!=
Not equal to
Checks if the values of two operands are not equal. Returns true if they are not equal, false otherwise.
x != y
>
Greater than
Checks if the value of the left operand is greater than the value of the right operand. Returns true if the condition is satisfied, false otherwise.
x > y
<
Less than
Checks if the value of the left operand is less than the value of the right operand. Returns true if the condition is satisfied, false otherwise.
x < y
>=
Greater than or equal to
Checks if the value of the left operand is greater than or equal to the value of the right operand. Returns true if the condition is satisfied, false otherwise.
x >= y
<=
Less than or equal to
Checks if the value of the left operand is less than or equal to the value of the right operand. Returns true if the condition is satisfied, false otherwise.
x <= y
For example :
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)
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.
The logical operators are:
Operator
Name
Description
Example
&&
Logical AND
Returns true if both operands are true, false otherwise. If the first operand evaluates to false, the second operand is not evaluated (short-circuit evaluation).
x && y
||
Logical OR
Returns true if at least one of the operands is true, false otherwise. If the first operand evaluates to true, the second operand is not evaluated (short-circuit evaluation).
x || y
!
Logical NOT
Returns the opposite boolean value of the operand. If the operand is true, it returns false, and if the operand is false, it returns true.
!x
&
Bitwise AND
Performs a bitwise AND operation on the binary representations of the operands. Each bit of the result is 1 if both corresponding bits in the operands are 1, otherwise, it is 0.
x & y
|
Bitwise OR
Performs a bitwise OR operation on the binary representations of the operands. Each bit of the result is 1 if at least one of the corresponding bits in the operands is 1, otherwise, it is 0.
x | y
^
Bitwise XOR
Performs a bitwise XOR (exclusive OR) operation on the binary representations of the operands. Each bit of the result is 1 if the corresponding bits in the operands are different, otherwise, it is 0.
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, condition, 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.
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.
The bitwise operators are:
Operator
Name
Description
Example
&
Bitwise AND
Performs a bitwise AND operation on the binary representations of the operands. Each bit of the result is 1 if both corresponding bits in the operands are 1, otherwise, it is 0.
x & y
|
Bitwise OR
Performs a bitwise OR operation on the binary representations of the operands. Each bit of the result is 1 if at least one of the corresponding bits in the operands is 1, otherwise, it is 0.
x | y
^
Bitwise XOR
Performs a bitwise XOR (exclusive OR) operation on the binary representations of the operands. Each bit of the result is 1 if the corresponding bits in the operands are different, otherwise, it is 0.
x ^ y
~
Bitwise NOT
Performs a bitwise NOT operation on the binary representation of the operand. It inverts all the bits, meaning that each 0 bit becomes 1, and each 1 bit becomes 0.
~x
<<
Left shift
Shifts the bits of the first operand to the left by the number of positions specified by the second operand. The leftmost bits are discarded, and zero bits are added on the right.
x << y
>>
Right shift
Shifts the bits of the first operand to the right by the number of positions specified by the second operand. The rightmost bits are discarded. The behavior of the added bits on the left depends on the sign bit of the operand (arithmetic or logical shift).
x >> y
>>>
Unsigned right shift
Shifts the bits of the first operand to the right by the number of positions specified by the second operand. The rightmost bits are discarded, and zero bits are added on the left. The sign bit is not extended, making it an unsigned shift.
x >>> y
For example :
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; }
You can also try this code with Online C++ Compiler
AND: 4
OR: 13
XOR: 9
NOT: -13
Left Shift: 24
Right Shift: 6
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.
The assignment operators are:
Operator
Name
Description
Example
=
Simple assignment
Assigns the value of the right operand to the left operand.
x = y
+=
Addition assignment
Adds the value of the right operand to the left operand and assigns the result to the left operand.
x += y
-=
Subtraction assignment
Subtracts the value of the right operand from the left operand and assigns the result to the left operand.
x -= y
*=
Multiplication assignment
Multiplies the value of the left operand by the right operand and assigns the result to the left operand.
x *= y
/=
Division assignment
Divides the value of the left operand by the right operand and assigns the result to the left operand.
x /= y
%=
Modulo assignment
Calculates the modulo (remainder) of the left operand divided by the right operand and assigns the result to the left operand.
x %= y
&=
Bitwise AND assignment
Performs a bitwise AND operation on the binary representations of the left and right operands and assigns the result to the left operand.
x &= y
|=
Bitwise OR assignment
Performs a bitwise OR operation on the binary representations of the left and right operands and assigns the result to the left operand.
x |= y
^=
Bitwise XOR assignment
Performs a bitwise XOR (exclusive OR) operation on the binary representations of the left and right operands and assigns the result to the left operand.
x ^= y
<<=
Left shift assignment
Shifts the bits of the left operand to the left by the number of positions specified by the right operand and assigns the result to the left operand.
x <<= y
>>=
Right shift assignment
Shifts the bits of the left operand to the right by the number of positions specified by the right operand and assigns the result to the left operand.
x >>= y
>>>=
Unsigned right shift assignment
Performs an unsigned right shift on the left operand by the number of positions specified by the right operand and assigns the result to the left operand.
x >>>= y
For example :
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; }
You can also try this code with Online C++ Compiler
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; }
You can also try this code with Online C++ Compiler
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.
What does cout << I << mean?
The expression cout << I; in C++ uses the output stream operator (<<) to send the value of the variable I to the standard output, typically the console.
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.