C Priority of Operator

Priority of Operator

Priority of Operator (Operator Precedence) determines the grouping of terms in an expression and decides how an expression is evaluated.
Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.

For example, x = 2 + 3 * 4; here, x is assigned 14, not 9 because operator * has a higher precedence than +, so it first gets multiplied with 3*4 and then adds into 2.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
 

Example:

/*Write a C Program to understand Operator precedence.*/
#include<stdio.h>
#include<conio.h>

void main()
{
    int a = 2;
    int b = 3;
    int c = 4;
    int ans;
    clrscr();

    ans = a + b * c ;
    printf("Value of %d + %d * %d is: %d\n",a,b,c,ans);

    ans = (a + b) * c;
    printf("Value of (%d + %d) * %d is: %d\n",a,b,c,ans);

    ans = a * b + c;
    printf("Value of %d * %d + %d is: %d\n",a,b,c,ans);

    ans = a * (b + c);
    printf("Value of %d * (%d + %d) is: %d\n",a,b,c,ans);

    getch();
}

Output:

Command Prompt
Value of 2 + 3 * 4 is: 14
Value of (2 + 3) * 4 is: 20
Value of 2 * 3 + 4 is: 10
Value of 2 * (3 + 4) is: 14


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question