Precedence and Associativity of Operators in C | Expressions in C

Preview

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

LevelOPERATORSASSOCIATIVITY
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
15COMMA 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.

Example

9+5-2*4

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.

Example

9<=4

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.

Example

9<=4 && 3<6

d. Bitwise Expression

The expression which contains bitwise operators is known as bitwise expression.

Example

10&7

e. Conditional Expression

The expression which contains conditional operator is known as conditional expression.

Example:

c=a>b?a:b;

Best Books of C





Lesson tags: Associativity of operators in c, precedence of operators in C
Back to: C Programming Language