In the section Introduction to programming, we had defined an expression as “A mathematical entity that evaluates to a value”. However, the term mathematical entity is somewhat vague. More precisely, an expression is a combination of literals, variables, operators, and functions that evaluates to a value.
A literal is simply a number, such as 5, or 3.14159. When we talk about the expression “3 + 4″, both 3 and 4 are literals. Literals always evaluate to themselves.
You have already seen variables and functions. Variables evaluate to the values they hold. Functions evaluate to produce a value of the function’s return type. Because functions that return void do not have return values, they are usually not part of expressions.
Literals, variables, and functions are all known as operands. Operands are the objects of an expression that are acted upon. Operands supply the data that the expression works with.
The last piece of the expressions puzzle is operators. Operators tell how to combine the operands to produce a new result. For example, in the expression “3 + 4″, the + is the plus operator. The + operator tells how to combine the operands 3 and 4 to produce a new value (7).
You are likely already quite familiar with standard arithmetic operators, including addition (+), subtraction (-), multiplication (*), and division (/). Assignment (=) is an operator as well.
Operators come in two types:
Unary operators act on one operand. An example of a unary operator is the – operator. In the expression
-5, the – operator is only being applied to one operand (5) to produce a new value (-5).
Binary operators act on two operands (known as left and right). An example of a binary operator is the + operator. In the expression
3 + 4, the + operator is working with a left operand (3) and a right operand (4) to produce a new value (7).
Note that some operators have more than one meaning. For example, the – operator has two contexts. It can be used in unary form to invert a number’s sign (eg. -5), or it can be used in binary form to do arithmetic subtraction (eg. 4 – 3).
This is just the tip of the iceberg in terms of operators. We will take an in-depth look at operators in more detail in a future section.
|1.6 — Whitespace and basic formatting|
|1.4 — A first look at functions|