Search code examples
coperator-precedence

How does operator precedence grouping work in C for *, /, and %?


Referring to the O'Reilly pocket reference for C, I'm a little confused by the description for grouping of the *, /, and % operators. The book says that grouping occurs left to right -- now I think I'm getting grouping confused with evaluation order. Given the following equation, and the rules established from the book, I would have thought that...

int x = 4 / 3 * -3

... evaluates to 0, because...

1: 4 / 3 * -3
2: 4 / -9
3: 0

... however, it actually evaluates to -3, and it seems to use this method...

1: 4 / 3 * -3
2: 1 * -3
3: -3

Why is that?


Solution

  • It makes sense to me:

    int x = 4 / 3 * -3;
    

    Grouping left to right, we get:

    int x = (4 / 3) * -3
    int x = ((4 / 3) * -3);
    

    Also see the precedence table. They are at the same precedence, so they bind left to right.