Precedence and Associativity of Operators in C
Precedence is the way to provide a priority to every operator. When more than one operator appear in an expression, they will be evaluated depending upon their precedence i.e. the operator with higher precedence will be evaluated first followed by the operator with lower precedence and so on.
For example, we want to calculate arithmetic expression 9+4/2. In this expression, the division operator (/) has more priority as compared to addition operator (+), so 4/2 will be solved first, then result of 4/2 will be added to 3 i.e. 2 will be added to 9 and output of expression would be 11.
In C language, priority to operators is assigned in the form of levels from 1 to 15, parenthesis and square brackets have the highest priority level and comma operator is having the lowest priority.
Associativity is the way to specify the order in which operators will be evaluated if more than one operator of same precedence appears in an expression.
Associativity can be either “Left to Right” or “Right to Left”. Associativity is predefined in C language. While solving an expression we must consider associativity along with precedence to solve an expression accurately.
Table to show Precedence and Associativity of Operators in C
|1||(), ||Left to Right|
|2||!, ~, ++, –, Unary +, Unary -, *, &, (type), sizeof() )||Right to Left|
|3||*, /, %||Left to Right|
|4||+ , –||Left to Right|
|5||<< , >>||Left to Right|
|6||<, <= , > , >=||Left to Right|
|7||= =, !=||Left to Right|
|8||&||Left to Right|
|9||^||Left to Right|
|10|||||Left to Right|
|11||&&||Left to Right|
|12||||||Left to Right|
|13||?:||Right to Left|
|14||=, +=, -=, /=, *=, ^=, !=, ,=, >>=||Left to Right|
|15||COMMA OPERATOR(,)||Left to Right|
Expressions in C
It is the combination of operators and operands. Expression is of various types:
a. Arithmetic Expression
The expression which contains arithmetic operators is known as arithmetic expression.
b. Relational Expression
The expression which contains relational operators is known as relational expression. The Output: of a relational expression is always 1 or 0.
c. Logical Expression
The expression which contains logical operators is known as logical expression. The Output: of a logical expression is always 1 or 0.
9<=4 && 3<6
d. Bitwise Expression
The expression which contains bitwise operators is known as bitwise expression.
e. Conditional Expression
The expression which contains conditional operator is known as conditional expression.
Best Books of C