Nimpo
Nimpo

Reputation: 444

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?

Upvotes: 0

Views: 98

Answers (2)

hyde
hyde

Reputation: 62777

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.

Upvotes: 1

Emma Leis
Emma Leis

Reputation: 2900

There's actually no difference. It uses d=1 and does a post-decrement in both cases.

The reason you see an apparent difference is that you're doing integer division, which rounds towards 0. That is: (int)1 / (int)10 = 0.

See the accepted answer on What is the behavior of integer division?

Upvotes: 5

Related Questions