Search code examples
coperator-precedence

Operator precedence in C explanation


I have the following code:

#include<stdio.h>
void main(){
int x;
x=1%9*4/5+8*3/9%2-9;
printf("%d \n", x);
}

The output of the program is -9. When I tried to breakdown the code according to operator precedence(* / %,Multiplication/division/modulus,left-to-right) answer turns out to be -8.

Below is the breakdown of the code:

x=1%9*4/5+8*3/9%2-9;
x=1%36/5+24/9%2-9;
x=1%7+2%2-9;
x=1+0-9;
x=-8;

Can someone explain how the output is -9.


Solution

  • It appears that you consider modulo to have lower precedence than multiplication and division, when in fact it does not. Instead of

    x = (1 % ((9 * 4) / 5)) + (((8 * 3) / 9) % 2) - 9;
    

    the expression you have really represents

    x = (((1 % 9) * 4) / 5) + (((8 * 3) / 9) % 2) - 9;
    

    The modulo in the first summand is applied before the multiplication and division.