C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.
Example:
C++ #include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }
Explanation: Here, '+' is an addition operator and does the addition of 10 and 20 operands and return value 30 as a result.
C++ Operator Types
C++ operators are classified into 6 types on the basis of type of operation they perform:
1. Arithmetic Operators
Arithmetic operators are used to perform arithmetic or mathematical operations on the operands. For example, '+' is used for addition.
Name | Symbol | Description |
---|
Addition | + | Adds two operands. |
---|
Subtraction | - | Subtracts second operand from the first. |
---|
Multiplication | * | Multiplies two operands. |
---|
Division | / | Divides first operand by the second operand. |
---|
Modulo Operation | % | Returns the remainder an integer division. |
---|
Increment | ++ | Increase the value of operand by 1. |
---|
Decrement | -- | Decrease the value of operand by 1. |
---|
Example:
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 8, b = 3; // Addition cout << "a + b = " << (a + b) << endl; // Subtraction cout << "a - b = " << (a - b) << endl; // Multiplication cout << "a * b = " << (a * b) << endl; // Division cout << "a / b = " << (a / b) << endl; // Modulo cout << "a % b = " << (a % b) << endl; // Increament cout << "++a = " << ++a << endl; // Decrement cout << "b-- = " << b--; return 0; }
Outputa + b = 11 a - b = 5 a * b = 24 a / b = 2 a % b = 2 ++a = 9 --b = 2
Important Points:
- The Modulo operator (%) operator should only be used with integers. Other operators can also be used with floating point values.
- ++a and a++, both are increment operators, however, both are slightly different. In ++a, the value of the variable is incremented first and then it is used in the program. In a++, the value of the variable is assigned first and then it is incremented. Similarly happens for the decrement operator.
You may have noticed that some operator works on two operands while other work on one. On the basis of this operators are also classified as:
- Unary: Works on single operand.
- Binary: Works on two operands.
- Ternary: Works on three operands.
2. Relational Operators
Relational operators are used for the comparison of the values of two operands. For example, '>' check right operand is greater.
Name | Symbol | Description |
---|
Is Equal To | == | Checks both operands are equal |
---|
Greater Than | > | Checks first operand is greater than the second operand |
---|
Greater Than or Equal To | >= | Checks first operand is greater than equal to the second operand |
---|
Less Than | < | Checks first operand is lesser than the second operand |
---|
Less Than or Equal To | <= | Checks first operand is lesser than equal to the second operand |
---|
Not Equal To | != | Checks both operands are not equal |
---|
Example
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 6, b = 4; // Equal operator cout << "a == b is " << (a == b) << endl; // Greater than operator cout << "a > b is " << (a > b) << endl; // Greater than Equal to operator cout << "a >= b is " << (a >= b) << endl; // Lesser than operator cout << "a < b is " << (a < b) << endl; // Lesser than Equal to operator cout << "a <= b is " << (a <= b) << endl; // Not equal to operator cout << "a != b is " << (a != b); return 0; }
Outputa == b is 0 a > b is 1 a >= b is 1 a < b is 0 a <= b is 0 a != b is 1
Note: 0 denotes false and 1 denotes true.
3. Logical Operators
Logical operators are used to combine two or more conditions or constraints or to complement the evaluation of the original condition in consideration. The result returns a Boolean value, i.e., true or false.
Name | Symbol | Description |
---|
Logical AND | && | Returns true only if all the operands are true or non-zero. |
---|
Logical OR | || | Returns true if either of the operands is true or non-zero. |
---|
Logical NOT | ! | Returns true if the operand is false or zero. |
---|
Example:
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 6, b = 4; // Logical AND operator cout << "a && b is " << (a && b) << endl; // Logical OR operator cout << "a || b is " << (a || b) << endl; // Logical NOT operator cout << "!b is " << (!b); return 0; }
Outputa && b is 1 a || b is 1 !b is 0
4. Bitwise Operators
Bitwise operators are works on bit-level. So, compiler first converted to bit-level and then the calculation is performed on the operands.
Name | Symbol | Description |
---|
Binary AND | & | Copies a bit to the evaluated result if it exists in both operands |
---|
Binary OR | | | Copies a bit to the evaluated result if it exists in any of the operand |
---|
Binary XOR | ^ | Copies the bit to the evaluated result if it is present in either of the operands but not both |
---|
Left Shift | << | Shifts the value to left by the number of bits specified by the right operand. |
---|
Right Shift | >> | Shifts the value to right by the number of bits specified by the right operand. |
---|
One's Complement | ~ | Changes binary digits 1 to 0 and 0 to 1 |
---|
Note: Only char and int data types can be used with Bitwise Operators.
Example:
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 6, b = 4; // Binary AND operator cout << "a & b is " << (a & b) << endl; // Binary OR operator cout << "a | b is " << (a | b) << endl; // Binary XOR operator cout << "a ^ b is " << (a ^ b) << endl; // Left Shift operator cout << "a<<1 is " << (a << 1) << endl; // Right Shift operator cout << "a>>1 is " << (a >> 1) << endl; // One’s Complement operator cout << "~(a) is " << ~(a); return 0; }
Outputa & b is 4 a | b is 6 a ^ b is 2 a<<1 is 12 a>>1 is 3 ~(a) is -7
5. Assignment Operators
Assignment operators are used to assign value to a variable. We assign the value of right operand into left operand according to which assignment operator we use.
Name | Symbol | Description |
---|
Assignment | = | Assigns the value on the right to the variable on the left. |
---|
Add and Assignment | += | First add right operand value into left operand then assign that value into left operand. |
---|
Subtract and Assignment | -= | First subtract right operand value into left operand then assign that value into left operand. |
---|
Multiply and Assignment | *= | First multiply right operand value into left operand then assign that value into left operand. |
---|
Divide and Assignment | /= | First divide right operand value into left operand then assign that value into left operand. |
---|
Example:
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 6, b = 4; // Assignment Operator. cout << "a = " << a << endl; // Add and Assignment Operator. cout << "a += b is " << (a += b) << endl; // Subtract and Assignment Operator. cout << "a -= b is " << (a -= b) << endl; // Multiply and Assignment Operator. cout << "a *= b is " << (a *= b) << endl; // Divide and Assignment Operator. cout << "a /= b is " << (a /= b); return 0; }
Outputa = 6 a += b is 10 a -= b is 6 a *= b is 24 a /= b is 6
6. Ternary or Conditional Operators
Conditional operator returns the value, based on the condition. This operator takes three operands, therefore it is known as a Ternary Operator.
Syntax:
C++ Expression1 ? Expression2 : Expression3
In the above statement:
- The ternary operator ? determines the answer on the basis of the evaluation of Expression1.
- If Expression1 is true, then Expression2 gets evaluated.
- If Expression1 is false, then Expression3 gets evaluated.
Example:
C++ #include <bits/stdc++.h> using namespace std; int main() { int a = 3, b = 4; // Conditional Operator int result = (a < b) ? b : a; cout << "The greatest number " "is " << result; return 0; }
OutputThe greatest number is 4
Miscellaneous Operators
Apart from these operators, there are a few operators that do not fit in any of the above categories. These are:
1. sizeof Operator
sizeof operator is a unary operator used to compute the size of its operand or variable in bytes. For example,
C++ sizeof (char); sizeof (var_name);
2. Comma Operator (,)
Comma operator is a binary operator that is used for multiple purposes. It is used as a separator or used to evaluate its first operand and discards the result; it then evaluates the second operand and returns this value (and type).
C++ int n = (m+1, m-2, m+5); int a, b, c;
6. Addressof Operator (&)
Addressof operator is used to find the memory address in which a particular variable is stored. In C++, it is also used to create a reference.
C++
5. Dot Operator(.)
Dot operator is used to access members of structure variables or class objects using their object names.
C++
3. Arrow Operator
Arrow operator is used to access the variables of classes or structures through its pointer.
C++
4. Casting Operators
Casting operators are used to convert the value of one data type to another data type. For example, for an integer value x:
C++ (float)x static_cast<float>(x)
Operator Precedency and Associativity
When there are multiple operators in a single expression, operator precedency and associativity decide in which order and which part of expression are calculate. Precedency tells which part of expression should be calculate first and associativity tells which direction to solve when same precedency operators are in expression.
Operator Precedence
Operator precedence says which operation is calculate first in the expression when expression have different precedency operators. For example:
3 * 2 + 8;
Will be evaluated as:
(3 * 2) + 8 = 14
It is because multiplication (*) have higher precedency then addition (+).
Operator Associativity
Operator associativity says if expression have more than one operator with same precedence then calculation happen in right to left or left to right.
50 / 25 * 2 = 1
Will be evaluated as:
(50 / 25) * 2
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem