In the C programming language, operators have a priority order that determines the order in which they are evaluated in an expression. Operators with a higher priority are evaluated before operators with a lower priority.
Here is the priority order of operators in C, from highest to lowest:
- () (parentheses)
- [] (array subscript)
- -> (structure pointer)
- . (structure member access)
- ! (logical NOT)
- ~ (bitwise NOT)
- ++ (increment)
- — (decrement)
-
- (unary minus)
-
- (dereference)
- & (address-of)
- sizeof
-
- (multiplication)
- / (division)
- % (modulo)
-
- (addition)
-
- (subtraction)
- << (left shift)
-
(right shift)
- < (less than)
- <= (less than or equal to)
-
(greater than)
-
= (greater than or equal to)
- == (equal to)
- != (not equal to)
- & (bitwise AND)
- ^ (bitwise XOR)
- | (bitwise OR)
- && (logical AND)
- || (logical OR)
- ?: (conditional)
- = (assignment)
- += (add and assign)
- -= (subtract and assign)
- *= (multiply and assign)
- /= (divide and assign)
- %= (modulo and assign)
- &= (bitwise AND and assign)
- ^= (bitwise XOR and assign)
- |= (bitwise OR and assign)
- , (comma)
It is important to use parentheses appropriately when writing expressions in C to ensure that the operators are evaluated in the correct order. For example, in the following expression:
a + b * c
The multiplication (b * c) will be evaluated before the addition (a + …), because the multiplication operator has a higher priority than the addition operator. To change the order of evaluation, we can use parentheses:
(a + b) * c
In this case, the addition (a + b) will be evaluated before the multiplication (* c), because the parentheses have the highest priority and force the addition to be evaluated first.