precedence and associativity of an operator in c

Precedence And Associativity Of Operators

Precedence of operators

If more than one operators are involved in an expression then, C language has predefined rule of priority of operators. This rule of priority of operators is called operator precedence.

In C, precedence of arithmetic operators(*,%,/,+,-) is higher than relational operators(==,!=,>,<,>=,<=) and precedence of relational operator is higher than logical operators(&&, || and !). Suppose an expression:

(a>b+c&&d)
This expression is equivalent to:
((a>(b+c))&&d)
i.e, (b+c) executes first
then, (a>(b+c)) executes
then, (a>(b+c))&&d) executes

Associativity of operators

Associativity indicates in which order two operators of same precedence(priority) executes. Let us suppose an expression:

a==b!=c

Here, operators == and != have same precedence. The associativity of both ==and != is left to right, i.e, the expression in left is executed first and execution take pale towards right. Thus, a==b!=cequivalent to :

(a==b)!=c

The table below shows all the operators in C with precedence and associativity.

Note: Precedence of operators decreases from top to bottom in the given table.

Summary of C operators with precedence and associativity
Operator Meaning of operator Associativity
()
[]
->
.
Functional call
Array element reference
Indirect member selection
Direct member selection
Left to right
!
~
+

++

&
*
sizeof
(type)
Logical negation
Bitwise(1 ‘s) complement
Unary plus
Unary minus
Increment
Decrement
Dereference Operator(Address)
Pointer reference
Returns the size of an object
Type cast(conversion)
Right to left
*
/
%
Multiply
Divide
Remainder
Left to right
+
Binary plus(Addition)
Binary minus(subtraction)
Left to right
<<
>>
Left shift
Right shift
Left to right
<
<=
>
>=
Less than
Less than or equal
Greater than
Greater than or equal
Left to right
==
!=
Equal to
Not equal to
Left to right
& Bitwise AND Left to right
^ Bitwise exclusive OR Left to right
| Bitwise OR Left to right
&& Logical AND Left to right
|| Logical OR Left to right
?: Conditional Operator Left to right
=
*=
/=
%=
-=
&=
^=
|=
<<=
>>=
Simple assignment
Assign product
Assign quotient
Assign remainder
Assign sum
Assign difference
Assign bitwise AND
Assign bitwise XOR
Assign bitwise OR
Assign left shift
Assign right shift
Right to left
, Separator of expressions Left to right

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s