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.
10 + 20
10 → Operand
+ → Operator
20 → Operand
Result → 30An 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.
total = marks + bonus;
marks → Operand
+ → Arithmetic Operator
bonus → Operand
= → Assignment Operator
total → Receives the ResultTypes 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.
| Operator | Meaning | Example |
|---|---|---|
| + | Addition | a + b |
| - | Subtraction | a - b |
| * | Multiplication | a * b |
| / | Division | a / b |
| % | Remainder | a % b |
#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;
}Addition : 30
Subtraction : 10
Multiplication : 200
Division : 2
Remainder : 0When 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.
std::cout << 5 / 2; // 2
std::cout << 5.0 / 2; // 2.52. 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.
#include <iostream>
int main()
{
int number;
number = 50;
std::cout << number;
return 0;
}50In 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.
| Operator | Meaning | Example |
|---|---|---|
| == | Equal to | a == b |
| != | Not equal to | a != b |
| > | Greater than | a > b |
| < | Less than | a < b |
| >= | Greater than or equal to | a >= b |
| <= | Less than or equal to | a <= b |
#include <iostream>
int main()
{
int a = 20;
int b = 10;
std::cout << (a > b);
return 0;
}1The 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.
| Operator | Meaning | Result |
|---|---|---|
| && | Logical AND | True when both operands are true |
| || | Logical OR | True when at least one operand is true |
| ! | Logical NOT | Reverses the logical value |
#include <iostream>
int main()
{
int age = 20;
std::cout << (age >= 18 && age <= 60);
return 0;
}age >= 18 → true
age <= 60 → true
true && true → true
Output → 1The && 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.
| Operator | Meaning | Example |
|---|---|---|
| ++ | Increase by one | count++ |
| -- | Decrease by one | count-- |
#include <iostream>
int main()
{
int count = 10;
count++;
std::cout << count;
return 0;
}11Both ++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.
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 11Memory Representation of Increment
Conceptually, incrementing a variable changes its stored value. The variable itself continues to refer to the same object.
Before:
int score = 50;
score
┌──────────────┐
│ 50 │
└──────────────┘
After:
score++;
score
┌──────────────┐
│ 51 │
└──────────────┘
The stored value changes from 50 to 51.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.
10 + 5 * 2
Step 1:
5 * 2 = 10
Step 2:
10 + 10 = 20
Result: 20Parentheses can explicitly control grouping and make expressions easier to understand. For example, (10 + 5) * 2 produces 30.
int result1 = 10 + 5 * 2; // 20
int result2 = (10 + 5) * 2; // 30Operator precedence determines how an expression is grouped. It does not, by itself, specify the runtime evaluation order of every operand.
Program Execution Flow
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
The = operator performs assignment, while == compares two values. Using assignment where comparison was intended can create incorrect program behavior.
Integer division by zero has undefined behavior. Always ensure the divisor is not zero before performing division or remainder operations.
The built-in remainder operator % requires integral operands. It cannot be directly applied to float or double values.
When both operands are integers, 5 / 2 produces 2 rather than 2.5.
The expression 2 + 3 * 4 produces 14 because multiplication is grouped before addition.
Expressions containing too many operators can become difficult to read and maintain. Break complicated calculations into clear intermediate steps.
// Assignment
age = 18;
// Comparison
age == 18if (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.