Operators & Expressions

⚡ C++ Lesson 4 Beginner

Operators perform mathematical and logical changes on values. Understanding arithmetic precedence (PEMDAS) and prefix/postfix increments is crucial.

1 Arithmetic Precedence & Increments

Operators follow mathematical precedence. Modulus (`%`) yields the remainder of a division. The placement of the increment operator (`++`) dictates execution order:

  • Postfix (`x++`): Evaluates `x` in the expression first, then increments `x`.
  • Prefix (`++x`): Increments `x` first, then evaluates the expression.
2 Logical & Relational Operators

Logical operators combine states: `&&` (AND), `||` (OR), and `!` (NOT) with short-circuit rules. Let's test these operators:

C++ — Operators & Precedence ▶ Run Code
#include <iostream>

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

    std::cout << "Integer Modulus (10 % 3): " << (a % b) << "\n";

    // Prefix vs Postfix increment tracing
    int x = 5;
    int y = x++; // y gets 5, then x becomes 6
    std::cout << "Postfix: y=" << y << ", x=" << x << "\n";

    int p = 5;
    int q = ++p; // p becomes 6, then q gets 6
    std::cout << "Prefix: q=" << q << ", p=" << p << "\n";

    return 0;
}
3 Code Challenge
Challenge: Declare an integer `val = 100`. Print the value of `val++` and `++val` to verify the execution order. Use logical operators to check if `val` is both greater than 50 and divisible by 2.