C++,  Programming

Operators in C++ – C++ – Lecture 10

The previous lecture broadened our understanding of data-types and their conversion. In this lecture, let us learn another interesting topic in detail, operators in C++.

What are Operators in C++?

In simple words, operators are used for performing mathematical operations on variables. Let us use the ‘+‘ operator to help you understand better.

int a = 5;
int b = 6;
int c = a + b;

Operand

In line 3, we use the + operator for performing addition of two variables. The variables a and b, on which we perform this operation, are known as operands.

Expression

An expression is a combination of operators, variables and constants. For example:

int c = a + b - 2;

Separator

Separator in C++ is used for separating variables, expressions or statements from each-other. For example: we can assign variables of same data-type in a single-line as shown below.

int x, y;
x = 1;
y = 2;
int a = 5, b = 2, c = 3;

Here, we use the ‘,‘ separator to separate variables and expressions. The ‘;‘ separator is used for separating statements(or lines, to help you understand) from each-other.

The Digit Separator in C++

Huge numbers in C++ can be a little inconvenient to read.

int revenue = 1000000;
// 10,00,000 is not allowed

To solve this problem, we can use digit separator(‘).

int revenue = 10'00'000;
int example = 100'000;

Note that the output still remains the same i.e., 1000000. The separator helps us in interpreting the number with ease. Alright, now let us talk about types of operators.

Types of Operators in C++

Operators are broadly classified into 3 categories:

  • Unary
  • Binary
  • Ternary

Unary Operator

This type of operator needs just one operand for operation. Most popular unary operators are:

  • +
  • (used before numbers)
  • ++(pre or post increment)
  • (pre or post decrement), 2 – are used
  • <<(left shift)
  • >>(right shift)

Binary Operator

These operators require two operands for operation. They are further divided into:

  • Arithmetic
  • Assignment
  • Relational
  • Logical
  • Bitwise

Ternary Operator

These operators require three operands for operation. They are used for conditional statements.

Apart from these operators, other operators which we already know are sizeof, typeof(tells us the data-type of variable at runtime), :: and so on.

We will learn more about operators later.

Operator Precedence in C++

Operator precedence is a rule that defines the order in which operators are evaluated. Just remember the order that,

Arithmetic(Multiplicative is evaluated before Additive) is evaluated before Logical is evaluated before Assignment.

I hope this article helped you in learning about the topic you were looking for. If you found this article helpful, share it with your friends and peers who want to learn programming in a fun way!

And I will see you in the next one😀.