When an expression contains multiple operators, C++ must decide which operator is applied first.
This decision is based on two rules: precedence and associativity.
Precedence determines which operator has priority when two operators share the same operand.
Example:
int flyingpigs = 3 + 4 * 5;
The * operator has higher precedence than +, so the expression is evaluated as:
3 + (4 * 5)
which produces 23, not 35.
Multiplication, division, and modulus (*, /, %) have the same precedence.
Addition and subtraction (+, -) share a lower precedence.
Parentheses can override precedence and force a different order.
If two operators have the same precedence and share the same operand, C++ applies associativity to decide which one goes first.
Example:
120 / 4 * 5
/ and * have equal precedence.
They also share operand 4.
C++ checks associativity: multiplication and division are left-to-right.
So evaluation goes as:
(120 / 4) * 5 = 30 * 5 = 150
If an operator is right-to-left associative, the right operator would go first.
Some operators in C++ behave that way (for example assignment).
Associativity is only relevant when two operators share the same operand.
Example:
int dues = 20 * 5 + 24 * 6;
Precedence says both multiplications happen before addition.
But 20 * 5 and 24 * 6 do not share an operand, so associativity does not determine which multiplication is performed first.
C++ leaves the order unspecified, and the compiler may choose whichever sequence works best for the system.
In this example the result is the same either way, but there are situations (such as with increment operators) where the order matters.