Each operator has a specific level of precedence, and operators with higher precedence are evaluated before those with lower precedence.
If operators have the same precedence, their associativity, which can be left-to-right or right-to-left, determines the order of evaluation.
Here's a simple example to illustrate operator precedence:
void main() {
int result = 2 + 3 * 4; // Multiplication (*) has higher precedence than addition (+)
print(result); // Output: 14
}
- In this example, the multiplication (
*
) operator has higher precedence than the addition (+
) operator. Therefore, the expression is evaluated as2 + (3 * 4)
, resulting in14
.
When operators have the same precedence and are left-to-right associative, the operations are performed from left to right.
dartCopy codeint result = 2 + 3 - 1;
// This is evaluated as (2 + 3) - 1
// First, addition is performed, then subtraction
// Result: 4
When operators have the same precedence and are right-to-left associative, the operations are performed from right to left.
dartCopy codeint result = 2 - 3 + 1;
// This is evaluated as 2 - (3 + 1)
// First, addition is performed, then subtraction
// Result: -2