03

Module 3: Operators and Expressions

Chapter 3 • Beginner

35 min

Operators and Expressions

Operators are symbols that perform operations on variables and values. Expressions combine variables, operators, and values to produce results.

What are Operators?

Operators are special symbols that tell the compiler to perform specific mathematical, logical, or relational operations.

Expressions are combinations of operators, variables, and values that evaluate to a single value.

Types of Operators

1. Arithmetic Operators

Perform mathematical operations.

OperatorOperationExampleResult
`+`Addition`5 + 3``8`
`-`Subtraction`10 - 4``6`
`*`Multiplication`3 * 4``12`
`/`Division`15 / 3``5`
`%`Modulus (remainder)`10 % 3``1`

Example:

cpp.js
int a = 10, b = 3;
int sum = a + b;        // 13
int diff = a - b;       // 7
int product = a * b;    // 30
int quotient = a / b;   // 3 (integer division)
int remainder = a % b;  // 1

Important Notes:

  • Integer division truncates (drops decimal part)
  • Modulus only works with integers
  • Division by zero causes runtime error

2. Assignment Operators

Assign values to variables.

OperatorExampleEquivalent To
`=``x = 5``x = 5`
`+=``x += 3``x = x + 3`
`-=``x -= 2``x = x - 2`
`*=``x *= 4``x = x * 4`
`/=``x /= 2``x = x / 2`
`%=``x %= 3``x = x % 3`

Example:

cpp.js
int x = 10;
x += 5;   // x is now 15
x -= 3;   // x is now 12
x *= 2;   // x is now 24
x /= 4;   // x is now 6

3. Increment and Decrement Operators

Increase or decrease value by 1.

OperatorNameEffect
`++x`Pre-incrementIncrement first, then use
`x++`Post-incrementUse first, then increment
`--x`Pre-decrementDecrement first, then use
`x--`Post-decrementUse first, then decrement

Example:

cpp.js
int a = 5;
int b = ++a;  // a becomes 6, b becomes 6
int c = a++;  // c becomes 6, a becomes 7

int x = 10;
int y = --x;  // x becomes 9, y becomes 9
int z = x--;  // z becomes 9, x becomes 8

4. Relational Operators

Compare two values and return true or false.

OperatorMeaningExampleResult
`==`Equal to`5 == 5``true`
`!=`Not equal to`5 != 3``true`
`>`Greater than`5 > 3``true`
`<`Less than`5 < 3``false`
`>=`Greater than or equal`5 >= 5``true`
`<=`Less than or equal`5 <= 3``false`

Example:

cpp.js
int age = 20;
bool isAdult = age >= 18;      // true
bool isTeen = age < 18;        // false
bool isExactly20 = age == 20;  // true

5. Logical Operators

Combine boolean expressions.

OperatorNameDescriptionExample
`&&`ANDBoth must be true`true && false` = `false`
``ORAt least one true`truefalse` = `true`
`!`NOTReverses boolean`!true` = `false`

Truth Tables:

AND (&&):

ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR (||):

ABAB
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT (!):

A!A
truefalse
falsetrue

Example:

cpp.js
int age = 20;
bool hasLicense = true;
bool canDrive = age >= 18 && hasLicense;  // true

int score = 85;
bool passed = score >= 60 || score == 100;  // true

bool isWeekend = false;
bool isWorkday = !isWeekend;  // true

6. Bitwise Operators

Operate on individual bits (advanced topic).

OperatorOperationExample
`&`AND`5 & 3` = `1`
``OR`53` = `7`
`^`XOR`5 ^ 3` = `6`
`~`NOT`~5`
`<<`Left shift`5 << 1` = `10`
`>>`Right shift`5 >> 1` = `2`

7. Conditional (Ternary) Operator

Shorthand for if-else statements.

Syntax: condition ? value_if_true : value_if_false

Example:

cpp.js
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
// status is "Adult"

int max = (a > b) ? a : b;  // Returns larger value

Operator Precedence

Operators are evaluated in a specific order when multiple operators appear in an expression.

Order (highest to lowest):

  1. Parentheses ()
  2. Unary operators (++, --, !, -)
  3. Multiplicative (*, /, %)
  4. Additive (+, -)
  5. Relational (<, >, <=, >=)
  6. Equality (==, !=)
  7. Logical AND (&&)
  8. Logical OR (||)
  9. Assignment (=, +=, etc.)

Example:

cpp.js
int result = 2 + 3 * 4;        // 14 (not 20!)
int result2 = (2 + 3) * 4;      // 20
bool check = 5 > 3 && 2 < 4;    // true

Best Practice: Use parentheses to make precedence clear, even when not necessary.

Type Conversions in Expressions

When different types are used in expressions, C++ performs automatic conversions.

Rules:

  1. Smaller types are promoted to larger types
  2. int + doubledouble
  3. char + intint

Example:

cpp.js
int a = 5;
double b = 3.5;
double result = a + b;  // a is converted to double, result is 8.5

Common Expressions

Mathematical Expressions

cpp.js
double area = 3.14159 * radius * radius;  // Circle area
double celsius = (fahrenheit - 32) * 5.0 / 9.0;  // Temperature conversion

Boolean Expressions

cpp.js
bool isValid = age >= 18 && age <= 65;
bool isWeekend = day == 6 || day == 7;
bool isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);

String Concatenation

cpp.js
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;  // "John Doe"

Best Practices

  1. Use parentheses for clarity, even when not needed
  2. Avoid complex expressions - break into multiple statements
  3. Be careful with integer division - use double if you need decimals
  4. Use meaningful variable names in expressions
  5. Understand operator precedence or use parentheses
  6. Avoid side effects in expressions (like ++ in complex expressions)

Common Mistakes

  • ❌ Forgetting that integer division truncates: 5 / 2 = 2 (not 2.5)
  • ❌ Using = instead of == in comparisons
  • ❌ Confusing && (logical) with & (bitwise)
  • ❌ Not understanding operator precedence
  • ❌ Modulus with floating-point numbers (only works with integers)

Next Module

In Module 4, we'll learn about Control Flow - how to make decisions with if/else statements and repeat code with loops!

Hands-on Examples

Arithmetic Operators

#include <iostream>
using namespace std;

int main() {
    int a = 15, b = 4;
    
    cout << "a = " << a << ", b = " << b << endl;
    cout << "Addition: " << a + b << endl;
    cout << "Subtraction: " << a - b << endl;
    cout << "Multiplication: " << a * b << endl;
    cout << "Division: " << a / b << endl;
    cout << "Modulus: " << a % b << endl;
    
    // Integer division note
    cout << "\nNote: Integer division truncates:" << endl;
    cout << "15 / 4 = " << (15 / 4) << " (not 3.75)" << endl;
    
    // For decimal division, use double
    double x = 15.0, y = 4.0;
    cout << "15.0 / 4.0 = " << (x / y) << endl;
    
    return 0;
}

This example demonstrates all basic arithmetic operators. Note that integer division truncates the decimal part. To get decimal results, use floating-point types (double or float).