Search code examples
coperator-precedenceoperationarithmetic-expressions

Misunderstood Operators Precedence in C


I was doing some exercises on the order of execution of operations in C and I came across a case that I did not quite understand.

int d = 1;
int e = d--/10;     // the result of e will be 0;

before calculating the value of "e", we decremented the "d" then we did the division.

on the other hand in "f", we made the division before decrementing the "d"!

int d = 1;
int f = 10/d--;     // the result of f will be: 10

My question is: why there is a differentiation in the value of "d" used knowing that in both cases the decrementation of "d" is a post-decrement?


Solution

  • For

    int e = d--/10;
    

    You say

    before calculating the value of "e", we decremented the "d" then we did the division.

    And this is the main source of your confusion. value of d was decremented after using it in division. It doesn't matter if it was in the expression before division, it is still post-decrement, and will happen after using the original value.

    You are also doing interger division, which rounds towards zero, which may add to your confusion.

    And in anticipation of possible follow-up question/experiment: if you have several post- or pre-increment or decrement operators in same expression for same variable, what actually happens is undefined. So just don't do that, results may change depending on compiler and optimization and whatnot.