×

C++ operator

In this article, we will discuss about the operators in C++ with their types and examples.

An operator is specially a symbol that tells compiler to perform specific manipulation. C++ contains various different types of operators. Operators are C++ symbols that instruct the compiler to carry out particular relational, logical, or mathematical operations. Operands are values or variables that undergo an operation.

Example Syntax:

int sum = 10 + 5;

Here, + is the operator and 5 and 10 are the operands.

In C++, various operators are available and are classified based on their functionality.

Types of C++ Operators:

  • Arithmetic Operators
  • Logical Operators
  • Relational Operators
  • Assignment Operators
  • Bitwise Operators
  • Misc. Operators

1. Arithmetic Operators:

Arithmetic operators are used to perform basic mathematical operation such as addition (+), subtraction (-), multiplication (*), division (/) etc.

OperatorDescriptionExample(x=5,y=5)Result
+Addition operatorx+y10
-Subtraction operatorx-y0
*Multiplication operatorx*y25
/Division operatorx/y1
%Modulus (Remainder) operatorx%y0

Example:

Let us take an example to illustrate the arithmetic operators in C++.

#include <iostream>

using namespace std;

int main() {

    int value1 = 5, value2 = 5;

    cout << "Addition: " << (value1 + value2) << endl;

    cout << "Subtraction: " << (value1 – value2) << endl;

    cout << "Multiplication: " << (value1 * value2) << endl;

    cout << "Division: " << (value1 / value2) << endl;

    cout << "Modulus: " << (value1 % value2) << endl;

    return 0;

}

Output:

Addition: 10

Subtraction: 0

Multiplication: 25

Division: 1

Modulus: 0

2. Logical operators:

Logical operators can be used to combine numerous variables and generate a Boolean (true or false) result.

OperatorDescriptionExample (x=true, y=false)Result
&&Logical ANDx&&yFalse
||Logical ORx||yLogical OR
!Logical NOTx!yFalse

Example:

Let us take an example to illustrate the logical operators in C++.

#include <iostream>

using namespace std;

int main() {

    bool x = true, y = false;

    cout << "x && y: " << (x && y) << endl;

    cout << "x || y: " << (x || y) << endl;

    cout << "!x: " << (!x) << endl;

    return 0;

}

Output:

x && y: 0

x || y: 1

!x: 0

3. Relational Operators:

Relational operations compare two values and return true or false. Relational operator shows the relation and compare between operands. Following are the different relational operations.

OperatorDescriptionExample (x=10, y= 20)Result
==Equal tox==yFalse
!=Not Equal tox!=yTrue
> Greater thanx>yTrue
< Less thanx<yFalse
>=Greater than equal tox>=yTrue
<=Less than equal tox<=yFalse

Example:

Let us take an example to illustrate the Relational operators in C++.

#include <iostream>

using namespace std;

int main() {

    int x = 10, y = 20 ;

    cout << "x == y: " << (x == y) << endl;

    cout << "x != y: " << (x != y) << endl;

    cout << "x > y: " << (x > y) << endl;

    cout << "x < y: " << (x < y) << endl;

    cout << "x >= y: " << (x >= y) << endl;

    cout << "x <= y: " << (x <= y) << endl;

    return 0;

}

Output:

x == y: 0

x != y: 1

x > y: 0

x < y: 1

x >= y: 0

x <= y: 1

4. Assignment Operators:

Assignment operators “=” assign values and modify variables using arithmetic operations. The assignment of value takes from right to left.

OperatorDescriptionExample (i=5)Equivalance
=Assigni=5i=5
+=Add and assigni+=5i=i+5
-=Subtract and assigni-=5i=i-5
*=Multiply and assigni*=5i=i*5
/=Divide and assigni/=5i=i/5
%=Modulus and assigni%=5i=i%5

Example:

Let us take an example to illustrate the Assignment operators in C++.

#include <iostream>

using namespace std;

int main() {

    int i = 10;

    i += 5;

    cout << "After i += 5: " << i << endl;

    i *= 2;

    cout << "After i *= 2: " << i << endl;

    return 0;

}

Output:

After i += 5: 15

After i *= 2: 30

5. Bitwise operator:

These Bitwise operators operate at the bit level. It is used to change individual bits into a number. Bitwise operators modify variable according to bit patterns. Following are the different bitwise operators:

OperatorDescriptionExample (i= 10 (1010), j=12(1100))
&Bitwise ANDi&j
||Bitwise OR
^Bitwise XORi^j
~Bitwise NOTi~j
<< Left Shifti<<j
>> Right Shifti>>j

Example:

Let us take an example to illustrate the Bitwise operators in C++.

#include <iostream>

using namespace std;

int main() {

    int i = 5, j = 3;

    cout << "i & j: " << (i & j) << endl;

    cout << "i | j: " << (i | j) << endl;

    cout << "i ^ j: " << (i ^ j) << endl;

    cout << "Left shift i << 1: " << (i << 1) << endl;

    cout << "Right shift j >> 1: " << (j >> 1) << endl;

    return 0;

}

Output:

i & j: 1

i | j: 7

i ^ j: 6

Left shift i << 1: 10

Right shift i >> 1: 2

6. Misc Operators:

Sizeof (sizeof): It returns the size (in bytes) of a variable or data type.

cout << sizeof(int); // Output: 4 (depends on system)

Pointer Operators (*, &): It is used for pointers and memory addresses.

int a = 10, *p = &a; 

cout << *p;  // Output: 10 

Comma Operator (,): It evaluates multiple expressions from left to right.

int x = (5, 10); // x = 10 

Cast Operators ((type), static_cast<>): It convert data types explicitly.

double d = 5.5; 

int x = (int)d; 

7. Precedence Operator:

The order in which an expression’s operators are evaluated depends on operator precedence. Higher priority operators are carried out before lower priority ones.

Example:

int result = 10 + 5 * 2;

The following table shows C++ operators in decreasing order of precedence:

PrecedenceOperatorDescriptionAssociativity
1 (Highest)      ::Scope resolutionLeft to Right
2     ++ --Post-increment, Post-decrementLeft to Right
3++ -- + - ! ~ * & sizeof type()Pre-increment, Pre-decrement, Unary plus/minus, Logical NOT, Bitwise NOT, Dereference, Address-of, Sizeof, TypecastRight to Left
4* / %Multiplication, Division, ModulusLeft to Right
5+ -Addition, SubtractionLeft to Right
6<< >>Bitwise Left and Right shiftLeft to Right
7< <= > >=Relational (less than, greater than, etc.)Left to Right
8== !=Equality and InequalityLeft to Right
9&Bitwise ANDLeft to Right
10^Bitwise XORLeft to Right
11|Bitwise ORLeft to Right
12&&Logical ANDLeft to Right
13||Logical ORLeft to Right
14?:Ternary (Conditional) OperatorRight to Left
15= += -= *= /= %= &= `= ^= <<= >>=`Assignment Operators
16 (Lowest),Comma Operator (Separates expressions)Left to Right

Conclusion:

In conclusion, operators play a very important part of C++ because they help in many computations, logical operations, and value manipulations done in a program. Different types of operators include bitwise, assignment, logical, relational, arithmetic, and many all with some individual significance. It is also important to understand operator precedence and associativity for proper evaluation of expressions. An operator with higher precedence gets evaluated first, while operators with the same precedence apply associativity rules. Precedence can be clear with the use of brackets, which also improves clarity and removes doubt. It helps programmers write meaningful codes in C++ by using the language construct effectively.


Related Topics

Differences between Local and Global Variable

Define Global Variable Global variables are those that may be accessible worldwide across a programme and are defined outside of any functions or blocks. It may be accessed by any function in...

3 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Find the Size of Array in C/C++ without using sizeof() function

We know that arrays in C/C++ are the most essential data structures as they have the ability to hold the data in a continuous manner line where the address of...

3 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

C++ First Program

Let's write a simple basic program structure of C++, its compilation and its execution (how it runs). This program is compiled using GCC compiler. Open any editor to write C++ program. #include<iostream>   using namespace std;   int main(){       cout<<"Welcome to C++ program"<<endl;   } Output...

2 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

Check for Balanced Brackets in an Expression (well-formedness) using Stack

Write a program that check the correctness of the pairs and ordering of the characters “{“, “}”, “(“, “)”, “[“, “]” in the expression string exp. Example: Checking for balanced parenthesis is one of...

2 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Constexpr in C++

Constexpr is a keyword in C++ that is used to declare variables or functions as compile-time constants. This means that the value of a constexpr variable or the return value...

3 minutes read.

Type difference of Character literals in C VS C++

Character literals in C: In C, a character literal is represented by a single character enclosed in single quotes, such as 'a' or 'b'. It is of type int. This means...

5 minutes read.

C++ Features

C++ is a general-purpose programming language that evolved from the C language to include an object-oriented paradigm. It is a compiled and imperative language. Object-Oriented Programming Object-oriented programming language concepts: ClassObjectsEncapsulationPolymorphismInheritanceAbstraction Class: A Class...

4 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

C++ Functions

In other programming languages, a function is referred to as a process or a subroutine. We can design functions to execute any task. A function can be used repeatedly. It...

5 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Multiset in C++

Introduction Multisets are part of the C++ STL, or Standard Template Library. In C++, a multiset is a set of associative containers that hold ordered items. Items in a multiset can...

10 minutes read.

Web Development in C++

Before learning above C++ web development, we need to learn about CGI What is CGI? CGI stands for common gateway interface. CGI is a standard that tells us how the exchange of...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.