cmacrosceil

Understanding CEILING macro use cases


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


Solution

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