Вопрос

While using Xcode, I accidentally auto completed to the macro howmany(x,y) and traced it to types.h. The entire line reads as follows:

#define howmany(x, y)   __DARWIN_howmany(x, y)  /* # y's == x bits? */

This didn't really make much sense, so I followed the path a little more and found __DARWIN_howmany(x, y) in _fd_def.h. The entire line reads as follows:

#define __DARWIN_howmany(x, y)  ((((x) % (y)) == 0) ? ((x) / (y)) : (((x) / (y)) + 1)) /* # y's == x bits? */

I have no idea what __DARWIN_howmany(x, y) does. Does the comment at the end of the line shed any light on the intended function of this macro? Could someone please explain what this macro does, how it is used, and its relevance in _fd_def.h

Это было полезно?

Решение 2

Based on what you've posted, the macro seems to be intended to answer a question like, "How many chars does it take to hold 18 bits?" That question could be answered with this line of code

int count = howmany( 18, CHAR_BIT );

which will set count to 3.

The macro works by first checking if y divides evenly into x. If so, it returns x/y, otherwise it divides x by y and rounds up.

Другие советы

This is a fairly commonly used macro to help programmers quickly answer the question, if I have some number of things, and my containers can each hold y of them, how many containers do I need to hold x things?

So if your containers can hold five things each, and you have 18 of them:

  n = howmany(18, 5);

will tell you that you will need four containers. Or, if my buffers are allocated in words, but I need to put n characters into them, and words are 8 characters long, then:

  n = howmanu(n, 8);

returns the number of words needed. This sort of computation is ubiquitous in buffer allocation code.

This is frequently computed:

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

Also related is roundup(x, y), which rounds x up to the next multiple of y:

#define roundup(x, y) (howmany(x, y)*(y))

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top