LearnContact
Lesson 910 min read

Operators

Now that we know how to store data, the next step is to perform operations on it. In this lesson, you will learn how C++ uses operators to perform calculations, compare values, and make decisions.

Introduction

In the previous lessons, you learned about data types and type conversion. Now that you know how to store different kinds of data, the next step is to perform operations on that data. Programs need to add numbers, calculate prices, compare values, check conditions, update scores, and make decisions. To perform these tasks, C++ provides operators.

Operators are among the most frequently used features in programming because almost every program performs calculations, comparisons, assignments, or logical evaluations.

What is an Operator?

An operator is a symbol that performs a specific operation on one or more values or expressions called operands.

Example
10 + 20

10      → Operand
+       → Operator
20      → Operand

Result  → 30
Simple Definition

An operator tells C++ what operation should be performed, while operands are the values or expressions on which that operation is performed.

Why Do We Need Operators?

Without Operators

  • Mathematical calculations could not be expressed.
  • Values could not be compared.
  • Logical conditions could not be combined.
  • Variables could not be updated through expressions.

With Operators

  • Perform mathematical calculations.
  • Compare values efficiently.
  • Build and combine logical conditions.
  • Assign, update, and manipulate values.

Real-World Analogy & Components of an Expression

Imagine a calculator. When you enter 5 + 3, the calculator uses the + symbol to perform addition and produces the result 8. C++ uses operators in a similar way to perform different kinds of operations.

Consider the expression total = marks + bonus;. It contains operands, operators, and a result that is assigned to a variable.

Expression Breakdown
total = marks + bonus;

marks      → Operand
+          → Arithmetic Operator
bonus      → Operand
=          → Assignment Operator
total      → Receives the Result

Types of Operators

C++ provides many categories of operators. This lesson focuses on the most commonly used operators for beginners.

Arithmetic Operators

Perform mathematical calculations such as addition, subtraction, multiplication, division, and remainder.

Assignment Operators

Store or update values in variables.

Relational Operators

Compare two values and produce a Boolean result.

Logical Operators

Combine or invert logical conditions.

Increment & Decrement

Increase or decrease a value by one.

1. Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric operands.

OperatorMeaningExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Remaindera % b
Example 1: Arithmetic Operators
#include <iostream>

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

    std::cout << "Addition : " << a + b << std::endl;
    std::cout << "Subtraction : " << a - b << std::endl;
    std::cout << "Multiplication : " << a * b << std::endl;
    std::cout << "Division : " << a / b << std::endl;
    std::cout << "Remainder : " << a % b;

    return 0;
}
Output
Addition : 30
Subtraction : 10
Multiplication : 200
Division : 2
Remainder : 0
Integer Division

When both operands are integers, integer division is performed. For example, 5 / 2 produces 2, not 2.5. To obtain a floating-point result, at least one operand must be a floating-point value.

Integer vs Floating-Point Division
std::cout << 5 / 2;      // 2
std::cout << 5.0 / 2;    // 2.5

2. Assignment Operator

The assignment operator = stores a value in an object such as a variable. The expression on the right side is evaluated, and the resulting value is assigned to the variable on the left side.

Example 2: Assignment
#include <iostream>

int main()
{
    int number;

    number = 50;

    std::cout << number;

    return 0;
}
Output
50
Assignment Direction

In number = 50;, the value on the right side is assigned to the variable on the left side. The assignment operator does not mean mathematical equality.

3. Relational Operators

Relational operators compare two operands. The result of a relational expression is a Boolean value: true or false.

OperatorMeaningExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b
Example 3: Relational Operator
#include <iostream>

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

    std::cout << (a > b);

    return 0;
}
Output
1
Boolean Output

The expression a > b evaluates to true. Without std::boolalpha, a Boolean value inserted into a standard output stream is normally displayed as 1 for true and 0 for false.

4. Logical Operators

Logical operators are used with conditions. They can combine multiple conditions or invert a condition.

OperatorMeaningResult
&&Logical ANDTrue when both operands are true
||Logical ORTrue when at least one operand is true
!Logical NOTReverses the logical value
Example 4: Logical Operator
#include <iostream>

int main()
{
    int age = 20;

    std::cout << (age >= 18 && age <= 60);

    return 0;
}
Condition Evaluation
age >= 18      → true
age <= 60      → true

true && true   → true

Output         → 1
Short-Circuit Evaluation

The && and || operators use short-circuit evaluation. With &&, the second operand is not evaluated if the first operand is false. With ||, the second operand is not evaluated if the first operand is true.

5. Increment and Decrement Operators

The increment and decrement operators increase or decrease a modifiable value by one.

OperatorMeaningExample
++Increase by onecount++
--Decrease by onecount--
Example 5: Increment
#include <iostream>

int main()
{
    int count = 10;

    count++;

    std::cout << count;

    return 0;
}
Output
11
Prefix and Postfix Forms

Both ++count and count++ increment count, but they behave differently when their resulting value is used inside a larger expression. This distinction becomes important in more advanced expressions.

Prefix vs Postfix
int a = 10;
int b = 10;

int x = ++a;   // a becomes 11, then x receives 11
int y = b++;   // y receives 10, then b becomes 11

Memory Representation of Increment

Conceptually, incrementing a variable changes its stored value. The variable itself continues to refer to the same object.

Conceptual Memory View
Before:

int score = 50;

score
┌──────────────┐
│      50      │
└──────────────┘

After:

score++;

score
┌──────────────┐
│      51      │
└──────────────┘

The stored value changes from 50 to 51.
About Memory Addresses

Actual memory addresses are determined at runtime and should not be represented as fixed values such as 1000 unless clearly marked as purely hypothetical.

Operator Precedence

When an expression contains multiple operators, precedence and associativity determine how the expression is grouped. For example, multiplication has higher precedence than addition.

Example
10 + 5 * 2

Step 1:
5 * 2 = 10

Step 2:
10 + 10 = 20

Result: 20
Use Parentheses for Clarity

Parentheses can explicitly control grouping and make expressions easier to understand. For example, (10 + 5) * 2 produces 30.

Changing the Grouping
int result1 = 10 + 5 * 2;      // 20
int result2 = (10 + 5) * 2;    // 30
Precedence Is Not Evaluation Order

Operator precedence determines how an expression is grouped. It does not, by itself, specify the runtime evaluation order of every operand.

Program Execution Flow

Program Starts
Evaluate Operands and Subexpressions
Apply Operators According to Expression Rules
Produce the Result
Store or Display the Result
Program Ends

Real-World Applications

Banking

Operators are used for calculations, comparisons, transaction limits, and account conditions.

Student Management

Operators calculate totals and percentages and help evaluate pass or fail conditions.

E-Commerce

Operators calculate prices, quantities, taxes, discounts, and eligibility conditions.

Gaming

Operators update scores, health, positions, counters, and game-state conditions.

Scientific Applications

Operators are used to evaluate formulas, compare measurements, and perform numerical calculations.

Common Beginner Mistakes

Confusing = with ==

The = operator performs assignment, while == compares two values. Using assignment where comparison was intended can create incorrect program behavior.

Dividing an Integer by Zero

Integer division by zero has undefined behavior. Always ensure the divisor is not zero before performing division or remainder operations.

Using % with Floating-Point Values

The built-in remainder operator % requires integral operands. It cannot be directly applied to float or double values.

Forgetting Integer Division

When both operands are integers, 5 / 2 produces 2 rather than 2.5.

Ignoring Operator Precedence

The expression 2 + 3 * 4 produces 14 because multiplication is grouped before addition.

Writing Overly Complex Expressions

Expressions containing too many operators can become difficult to read and maintain. Break complicated calculations into clear intermediate steps.

Assignment vs Comparison
// Assignment
age = 18;

// Comparison
age == 18
Check Before Division
if (divisor != 0)
{
    int result = number / divisor;
}

Best Practices

  • Use parentheses when they make the intended grouping clearer.
  • Choose the correct operator for the operation being performed.
  • Break complicated expressions into smaller, meaningful steps.
  • Be careful to distinguish assignment = from comparison ==.
  • Check divisors before performing integer division or remainder operations.
  • Remember that integer division discards the fractional part.
  • Avoid depending on side effects inside complicated expressions.
  • Use meaningful variable names so expressions are easier to understand.

Frequently Asked Questions

What is an operator?

An operator is a symbol or keyword that performs an operation on one or more operands.

What are operands?

Operands are the values or expressions on which an operator performs its operation.

Which operator performs addition?

The + operator performs addition for numeric operands.

Which operator compares two values for equality?

The == operator compares two values for equality.

Which operator assigns a value?

The = operator performs assignment.

What does && mean?

The && operator means logical AND. Its result is true only when both operands evaluate to true.

Why does 5 / 2 produce 2?

Because both operands are integers, C++ performs integer division and discards the fractional part.

Can % be used with float or double?

No. The built-in % operator requires integral operands.

Key Takeaways

  • Operators perform operations on operands.
  • Arithmetic operators perform mathematical calculations.
  • The assignment operator stores or updates values.
  • Relational operators compare values and produce Boolean results.
  • Logical operators combine or invert conditions.
  • Increment and decrement operators modify values by one.
  • Integer division behaves differently from floating-point division.
  • The % operator works with integral operands.
  • Operator precedence determines how expressions are grouped.
  • Parentheses can improve clarity and explicitly control grouping.

Summary

Operators are essential building blocks of C++ programming because they allow programs to calculate values, compare data, evaluate conditions, assign results, and update variables. Arithmetic, assignment, relational, logical, increment, and decrement operators appear throughout C++ programs. Understanding how these operators behave, including integer division, short-circuit evaluation, and operator precedence, provides the foundation for writing correct and readable expressions.

Next Lesson →

Input & Output