I'm working with the code that frequently uses some nontrivial optimizations. What is the
#define idiv(a, b) (((a) + (b) / 2) / (b))
used for? Why not simply
#define idiv(a, b) ((a)/(b) + 0.5)
Is it integer division overflow protection or something else?
Integer division truncates towards zero. Assuming (from the name of the macro, idiv) your arguments are of integer type, ((a)/(b) + 0.5)
would be truncated before you got to the + 0.5
, so you would always round down regardless.
(((a) + (b) / 2) / (b))
rounds up results greater than x.5, without using floating-point arithmetics.
Note: You tagged your question C++. In C++, you shouldn't "macro" anything, really. Check Marek's answer for a template solution (but also the caveat that it doesn't really work for negative values).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With