Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the following C++ code used for -> "#define idiv(a, b) (((a) + (b) / 2) / (b))"?

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?

like image 765
Alan Kazbekov Avatar asked Dec 06 '22 08:12

Alan Kazbekov


1 Answers

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).

like image 176
DevSolar Avatar answered Mar 04 '23 11:03

DevSolar