LEVIATHAN v962456e · 962456eee1

Expressions

Operator precedence

The binding strength and associativity of every operator, from loosest to tightest.

since 0.1.0-alpha.1linuxwindowswasm

Description

When an expression mixes operators without parentheses, the operator with the higher level binds first. The table lists the levels from the loosest (level 1) to the tightest (the postfix forms). Operators on one level group according to their associativity: a left-associative level groups from the left (7 - 2 - 1 is (7 - 2) - 1), and a right-associative level groups from the right (a = b = 4 assigns 4 to b first).

level operators associativity
1 = += -= *= /= %= right
2 ?: (ternary), .. (range) right
3 || left
4 && left
5 | & ^ left
6 == != left
7 < > <= >= left
8 << >> left
9 + - left
10 * / % left
prefix ! - ~ none
postfix .name ::name ::<types>(args) (args) [index] left

Prefix operators bind tighter than every binary operator and looser than the postfix forms, so -2.abs() negates the result of 2.abs(). Parentheses override every level.

Two bindings that surprise C programmers

// `+` binds tighter than `<<`: this is 1 << (2 + 1), not (1 + 2) << 1.
console.writeln(1 << 2 + 1);

// `&&` binds tighter than `||`: this is true || (false && false).
console.writeln(true || false && false);

// Postfix binds tighter than prefix: this is -(2.abs()).
console.writeln(-2.abs());

// Assignment is right-associative.
int a = 0;
int b = 0;
a = b = 4;
console.writeln("${a} ${b}");

// Parentheses override the table.
console.writeln((1 + 2) << 1);
8
true
-2
4 4
6

Rules

  • A higher level binds before a lower level; parentheses always win.
  • Levels 3 to 10 and the postfix forms are left-associative. Assignment (level 1) and the ternary and range operators (level 2) are right-associative.
  • The bitwise operators |, & and ^ share one level, so a mix of them groups strictly from the left: 6 & 3 | 4 ^ 1 is ((6 & 3) | 4) ^ 1.
  • The equality operators bind looser than the relational operators, so 1 < 2 == true compares the result of 1 < 2 with true.
  • A range (..) binds looser than arithmetic, so 0..2 + 1 is the range from 0 to 3.

Examples

Shared level and chained comparisons

console.writeln(6 & 3 | 4 ^ 1);
console.writeln(7 - 2 - 1);
console.writeln(1 < 2 == true);
for (int i in 0..2 + 1) {
    console.write("${i}");
}
console.writeln("");
7
4
true
0123

Notes

Where the intent is not obvious to a reader, add parentheses even when the table makes them redundant.

See also

  • int — The signed 64-bit integer type, the default type of whole numbers.
  • bool — The boolean type: a value is either true or false.