Lesson 13 +10 XP

Introduction to Expressions

Introduction to Expressions

Programs don't just echo values, they compute them. The engine of every computation is an expression.

What is an expression?

An expression is a combination of values, variables, and operators that produces a single value:

5 + 3        // 8
x * 2        // depends on x
2 * 3 + 4    // 10

Operators and operands

Every expression has parts:

  • Operand - a value or variable a math uses (the numbers).
  • Operator - what you do to them (like +, -, *, /).

In x + 5, the operands are x and 5, and the operator is +.

Evaluating in order: precedence

C++ follows the usual math order of operations:

  1. Parentheses first.
  2. Multiplication and division.
  3. Then addition and subtraction.
int a = 2 + 3 * 4;     // 2 + 12 = 14
int b = (2 + 3) * 4;   // 5   * 4 = 20

Expression statements

Lots of "statements" are really expressions ended with a semicolon:

int x = 1 + 2; // x becomes 3
cout << x;     // prints the value of x

The result of an expression gets stored or output immediately; the expression itself is evaluated once.

TL;DR

  • An expression combines values and operators to produce a value.
  • In x + 5, x and 5 are operands, + is the operator.
  • Order matters: (), then */, then +- .
  • Expression + semicolon = expression statement, e.g. int y = 2 * 3;.