Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding CEILING macro use cases

Tags:

c

macros

ceil

I've found the following macro in a utility header in our codebase:

#define CEILING(x,y) (((x) + (y) - 1) / (y))

Which (with help from this answer) I've parsed as:

// Return the smallest multiple N of y such that:
//   x <= y * N

But, no matter how much I stare at how this macro is used in our codebase, I can't understand the value of such an operation. None of the usages are commented, which seems to indicate it is something obvious.

Can anyone offer an English explanation of a use-case for this macro? It's probably blindingly obvious, I just can't see it...

like image 564
tdenniston Avatar asked Jul 06 '12 13:07

tdenniston


2 Answers

Say you want to allocate memory in chunks (think: cache lines, disk sectors); how much memory will it take to hold an integral number of chunks that will contain the X bytes? If the chuck size is Y, then the answer is: CEILING(X,Y)

like image 200
Doug Currie Avatar answered Oct 19 '22 23:10

Doug Currie


When you use an integer division in C like this

y = a / b

you get a result of division rounded towards zero, i.e. 5 / 2 == 2, -5 / 2 == -2. Sometimes it's desirable to round it another way so that 5 / 2 == 3, for example, if you want to take minimal integer array size to hold n bytes, you would want n / sizeof(int) rounded up, because you want space to hold that extra bytes.

So this macro does exactly this: CEILING(5,2) == 3, but note that it works for positive y only, so be careful.

like image 40
unkulunkulu Avatar answered Oct 20 '22 00:10

unkulunkulu