if anyone could answer me why this works, it would be greatly appreciated. The exercise (chapter 4, ex 7 and 8) says that if you have the expression:
9 – ((total – 1) % 10)
then, you could be tempted to simplify it like this:
10 – (total % 10)
But this would not work. Instead he offers the alternative:
(10 – (total % 10)) % 10
Now, I understand how he got to the first simplification, but not why it’s wrong, or why does the second one works.
Thanks in advance
Consider the outputs for
total = 10to see that the second expression is not equivalent.Note also that the third expression is not equivalent to the first expression unless
total > 0(because the behaviour of%is implementation-defined in pre-C99 C, and defined but not what you want in C99).Assuming that
total > 0, the first and third expressions are equivalent due to the following mathematical identity:To understand why, imagine doing the operations on a clock-face.