Operators
In short: Symbols that perform an operation on one or more values — from simple arithmetic (+, -) through comparisons (==, <) to logical combination (&&, ||).
In more detail: Operators can roughly be divided into categories: arithmetic (calculations), assignment (setting/changing values), comparison (result is true/false), and logical operators (combining conditions). If an expression contains several operators, operator precedence decides the order in which they’re evaluated.
In Depth
An operator combines one or more values (the “operands”) into a new result value. By the number of operands, a distinction is made:
- Unary operators: need only ONE operand, e.g. the sign (
-5) or negation (!true). - Binary operators: need TWO operands, the vast majority of all operators (
3 + 4,a == b). - Ternary operators: need THREE operands — the best known is the conditional expression
condition ? ifTrue : ifFalse, a compact shorthand for a simple if…else.
age >= 18 ? "adult" : "minor"
// equals:
// if (age >= 18) { "adult" } else { "minor" }A special group is compound assignment operators (see Assignment Operators) like +=, which combine an operation and an assignment in one step (x += 5 equals x = x + 5) — shorter to write and less error-prone, because the variable name appears only once instead of twice.
Many languages also allow operator overloading — assigning the same symbols (+, ==) a custom, meaningful meaning for your own types as well (e.g. + for combining two custom vector objects). This can make code very readable, but is easily misused when the overloaded meaning doesn’t match intuitive expectations (a + that, say, secretly deletes a file would be extremely surprising and poor style).
See also: Arithmetic Operators, Comparison Operators, Logical Operators, Operator Precedence