Erin's CS stuff

CS stuff!

Operator Precedence and Associativity

While there are more operators than these in C, we will primarily be using the following:

Symbol [1] Type of operation Associativity
++ -- (postfix) Expression Left to right
* / % Multiplicative Left to right
+ - Additive Left to right
< > <= >= Relational Left to right
== != Equality Left to right
&& Logical-AND Left to right
|| Logical-OR Left to right
= *= /= %=
+= -=
Simple and compound assignment [2] Right to left
, Sequential evaluation Left to right

1 Operators are listed in descending order of precedence. If several operators appear on the same line or in a group, they have equal precedence.

2 All simple and compound-assignment operators have equal precedence.

An expression can contain several operators with equal precedence. When several such operators appear at the same level in an expression, evaluation proceeds according to the associativity of the operator, either from right to left or from left to right.

Only the sequential-evaluation (,), logical-AND (&&), and logical-OR (||) operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands. The function-call operator is the set of parentheses following the function identifier. The sequential-evaluation operator (,) is guaranteed to evaluate its operands from left to right. (The comma operator in a function call is not the same as the sequential-evaluation operator and does not provide any such guarantee.)

Logical operators also guarantee evaluation of their operands from left to right. However, they evaluate the smallest number of operands needed to determine the result of the expression. This is called "short-circuit" evaluation. Thus, some operands of the expression may not be evaluated. For example, in the expression

x && y++

the second operand, y++, is evaluated only if x is true (nonzero). Thus, y is not incremented if x is false (0).

This table is based on https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=msvc-170 with examples and explanations outside the scope of this course removed.