Expressions
Expressions combine an operator (symbol representing behavior) with one or more operands (values). The expression results in another value, through a process we call "evaluation".
Syntax
Most of the operators we'll use are either "unary" or "binary"[1]. Unary means the operator works with one operand, while binary means the operator works with two operands.
counter++
is an expression where counter
is the operand and ++
is the unary operator.[2]
counter + 1
is an expression where counter
is the first operand, 1
is the second operand, and +
is the binary operator.[3]
NOTE: I haven't included semicolons to emphasize that these are expressions not statements.
Behavior
Evaluation
Each of our example expressions,
counter++
and counter + 1
"evaluate to" (or result in) a value that is 1 more than whatever is stored in counter
. For example, if counter
was storing a value of 0
, then these expressions "evaluate" to 1
.
Because all of our code is being broken to simpler instructions, the computer has to evaluate individual operator expressions one at a time. When we have more complex expressions with multiple operators, we need to understand what order the operators are evaluated in to know what the resulting value will be. This is determined by operator precedence and associativity.
Operator precedence is the priority operators are given to be evaluated first. Arithmetic operators generally follow a PEMDAS approach.
Associativity applies to multiple operators of the same precedence. Generally, binary operators have left to right associativity.
Here's a breakdown of relevant Precedence and Associativity
Side Effects
A side effect is behavior in your programming that happens in addition to evaluation. Often, side effects make a change or modify a variable. For example, the expression in this
counter = 0;
statement evaluates to 0
but we use the assignment operator for its side effect, which is to change the value of counter
to 0
.
Similarly, the expression in this
counter++;
statement evaluates to 1
but we use the postfix increment operator for its side effect, which is to increase the value of counter
from 0
to 1
.
The postfix and assignment operators (both simple and compound) are generally used for their side effects and any "evaluation" is ignored.
1. There are occasionally “ternary” operators which include three operands.
2. Unary operators can be in front of the operand (prefex) or after the operand (postfix). Most programmers use the postfix format, as it has a higher precedence.
3. Binary operators use an infix format, where the operator goes between the operands. That is not true of all languages (>.> I’m looking at you, Lisp).