Reading Operator Precedence
Group an expression according to the language's rules, then use parentheses to make the intended calculation visible to a reader.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 2 min
In this article4 chapters
Compute from the tree
With 8 + 4 * 3, multiplication has higher precedence than addition in Python. The main operation is addition, and its right operand evaluates to twelve. The result is twenty. With (8 + 4) * 3, the main operation is multiplication and the result is thirty-six. Expression evaluation follows the grouping established by the grammar.
Make the boundary obvious
Suppose a workshop offers a discount of two credits per ticket. For three tickets at eight credits each, (8 - 2) * 3 gives eighteen. The expression 8 - 2 * 3 gives two and describes a different calculation. Include a case with several tickets in tests around input boundaries, so a one-ticket case cannot hide the grouping mistake.[1][2]
Draw an expression tree for a real calculation
Suppose a delivery costs four credits plus three credits per kilogram, and a two-credit discount applies to the whole delivery. On a five-kilogram package the intended expression is (4 + 3 * 5) - 2. Within the first group, multiplication produces fifteen, addition makes nineteen, and subtraction gives seventeen. You can draw the root as subtraction with an addition result as its left child. The multiplication is a child of that addition.
If the discount is per kilogram instead, the rule changes to 4 + (3 - 2) * 5, giving nine. Values of one kilogram happen to produce five under both rules. A test only at that weight would miss the difference. Choosing inputs with different expected results helps verify which interpretation is actually implemented.
Check precedence and grouping separately
Precedence explains grouping for different operators. Associativity can decide the grouping of repeated operators, as in a chain of subtractions. Under a usual left-associative rule, 30 - 8 - 2 means (30 - 8) - 2 and gives twenty. Parentheses can intentionally ask for 30 - (8 - 2), which gives twenty-four. See associativity in an expression tree for why the parse changes.
Mixing arithmetic with conditions deserves the same care. Write “shipping is free if the subtotal reaches the threshold or a waiver was entered, and the destination is supported” as two named checks if the grouping is hard to read. Test a waived order with an unsupported destination. A truth table can expose what either grouping actually authorizes.