Loading lessons...
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:
cpp
### 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:
- Parentheses first.
- Multiplication and division.
- Then addition and subtraction.
cpp
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:
cpp
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,xand5are operands,+is the operator. - Order matters: (), then */, then +- .
- Expression + semicolon = expression statement, e.g.
int y = 2 * 3;.