5.2 Operator Overview
In this table, the column labeled "P" gives the operator precedence and the column labeled "A" gives the operator associativity, which can be L (left-to-right) or R (right-to-left). If you do not already understand precedence and associativity, the subsections that follow the table explain these concepts. The operators themselves are documented following that discussion.
5.2.1 Number of Operands
5.2.2 Type of Operands
Furthermore, some operators behave differently depending on the type of the operands. Most notably, the + operator adds numeric operands but concatenates string operands. Also, if passed one string and one number, it converts the number to a string and concatenates the two resulting strings. For example, "1" + 0 yields the string "10".
5.2.3 Operator Precedence
In Table 5-1, the column labeled "P" specifies the precedence of each operator. Operator precedence controls the order in which operations are performed. Operators with higher numbers in the "P" column are performed before those with lower numbers.
Consider the following expression:
w = x + y*z;
The multiplication operator * has a higher precedence than the addition operator +, so the multiplication is performed before the addition. Furthermore, the assignment operator = has the lowest precedence, so the assignment is performed after all the operations on the righthand side are completed.
Operator precedence can be overridden with the explicit use of parentheses. To force the addition in the previous example to be performed first, we would write:
w = (x + y)*z;
In practice, if you are at all unsure about the precedence of your operators, the simplest thing is to use parentheses to make the evaluation order explicit. The only rules that are important to know are these: multiplication and division are performed before addition and subtraction, and assignment has very low precedence and is almost always performed last.
5.2.4 Operator Associativity
In Table 5-1, the column labeled "A" specifies the associativity of the operator. A value of L specifies left-to-right associativity, and a value of R specifies right-to-left associativity. The associativity of an operator specifies the order in which operations of the same precedence are performed. Left-to-right associativity means that operations are performed from left to right. For example, the addition operator has left-to-right associativity, so:
w = x + y + z;
is the same as:
w = ((x + y) + z);
On the other hand, the following (almost nonsensical) expressions:
x = ~-~y; w = x = y = z; q = a?b:c?d:e?f:g;
are equivalent to:
x = ~(-(~y)); w = (x = (y = z)); q = a?b:(c?d:(e?f:g));