Operator Precedence in the C Computer Language
Part 27 of the Complete C Course
Foreword: Operator Precedence in the C Computer Language
By: Chrysanthus Date Published: 22 Jun 2024
Introduction
Example
Consider the following statement:
int x = 2 + 8 % 5;
There are three operators here, which are =, + and %. Now = is of a very low precedence and it is executed last, in this statement. The question then is between + and %; which is executed first? If the modulus operator, % is executed first, the answer will be 5. If the Addition operator is executed first, the answer will be 0. Well, in C, % is of a higher precedence than +, so % is executed first and the answer will become 5. '+' can be forced to be executed first, by using brackets, as follows:
int x = (2 + 8) % 5;
Whenever in doubts of which operator should be executed first, use brackets, to force an operator to be executed first. Brackets can be nested.
Precedence Order
The precedence order for operators are given below. The highest precedence is given first; that is followed by the second precedence, then the third, and so on, until the last. If a binary operator operates with the right operand first, then that is right associativity. If a binary operator operates with the left operand first, then that is left associativity.
Scope Resolution Operator
::
Associativity (direction of operation): Left-to-right
Postfix Operators
() [] . -> ++ --
Associativity: Left-to-right
Unary Prefix Operators
++ -- ~ ! sizeof new delete
Associativity: Right-to-left
Reference and Indirection Operators
& *
Associativity: Right-to-left
Unary Sign Operators
+ -
Associativity: Right-to-left
Type Casting Operators
(type)
Associativity: Right-to-left
Pointer-to-member Operators
.* ->*
Associativity: Left-to-right
Multiplicative Operators
% * /
Associativity: Left-to-right
Additive Operators
+ -
Associativity: Left-to-right
Bitwise Shift Operators
<< >>
Associativity: Left-to-right
Relational Operators
< > <= >=
Associativity: Left-to-right
Equality Operators
== !=
Associativity: Left-to-right
Bitwise AND Operator
&
Associativity: Left-to-right
Bitwise XOR Operator
^
Associativity: Left-to-right
Bitwise OR Operator
|
Associativity: Left-to-right
Logical AND Operator
&&
Associativity: Left-to-right
Logical OR Operator
||
Associativity: Left-to-right
Conditional Operator
?:
Associativity: Right-to-left
Assignment Operators
= *= /= %= += -= >>= <<= &= ^= !=
Associativity: Right-to-left
Comma Operator
,
Associativity: Left-to-right