Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

C++ Programming

Operators and Expressions

Mastering operators and expressions concepts and implementation.

On this page

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
+Addition5 + 38
-Subtraction10 - 46
*Multiplication3 * 412
/Division15 / 35
%Modulus (remainder)10 % 31

Example:

1int a = 10, b = 3;
2int sum = a + b;        // 13
3int diff = a - b;       // 7
4int product = a * b;    // 30
5int quotient = a / b;   // 3 (integer division)
6int 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 = 5x = 5
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4
/=x /= 2x = x / 2
%=x %= 3x = x % 3

Example:

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

3. Increment and Decrement Operators

Increase or decrease value by 1.

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

Example:

1int a = 5;
2int b = ++a;  // a becomes 6, b becomes 6
3int c = a++;  // c becomes 6, a becomes 7
4 
5int x = 10;
6int y = --x;  // x becomes 9, y becomes 9
7int z = x--;  // z becomes 9, x becomes 8

4. Relational Operators

Compare two values and return true or false.

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
>Greater than5 > 3true
<Less than5 < 3false
>=Greater than or equal5 >= 5true
<=Less than or equal5 <= 3false

Example:

1int age = 20;
2bool isAdult = age >= 18;      // true
3bool isTeen = age < 18;        // false
4bool isExactly20 = age == 20;  // true

5. Logical Operators

Combine boolean expressions.

OperatorNameDescriptionExample
&&ANDBoth must be truetrue && 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:

1int age = 20;
2bool hasLicense = true;
3bool canDrive = age >= 18 && hasLicense;  // true
4 
5int score = 85;
6bool passed = score >= 60 || score == 100;  // true
7 
8bool isWeekend = false;
9bool isWorkday = !isWeekend;  // true

6. Bitwise Operators

Operate on individual bits (advanced topic).

OperatorOperationExample
&AND5 & 3 = 1
``OR`53 = 7`
^XOR5 ^ 3 = 6
~NOT~5
<<Left shift5 << 1 = 10
>>Right shift5 >> 1 = 2

7. Conditional (Ternary) Operator

Shorthand for if-else statements.

Syntax: condition ? value_if_true : value_if_false

Example:

1int age = 20;
2string status = (age >= 18) ? "Adult" : "Minor";
3// status is "Adult"
4 
5int 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:

1int result = 2 + 3 * 4;        // 14 (not 20!)
2int result2 = (2 + 3) * 4;      // 20
3bool 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 + double → double
  3. char + int → int

Example:

1int a = 5;
2double b = 3.5;
3double result = a + b;  // a is converted to double, result is 8.5

Common Expressions

Mathematical Expressions

1double area = 3.14159 * radius * radius;  // Circle area
2double celsius = (fahrenheit - 32) * 5.0 / 9.0;  // Temperature conversion

Boolean Expressions

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

String Concatenation

1string firstName = "John";
2string lastName = "Doe";
3string 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).

Sample Output

a = 15, b = 4
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3
Modulus: 3

Note: Integer division truncates:
15 / 4 = 3 (not 3.75)
15.0 / 4.0 = 3.75