Question about round_up macro

前端 未结 5 751
暗喜
暗喜 2021-02-07 12:55
#define ROUND_UP(N, S) ((((N) + (S) - 1) / (S)) * (S))

With the above macro, could someone please help me on understanding the \"(s)-1\" part, why\'s t

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-07 13:28

    Based on the current draft standard (C99) this macro is not entirely correct however, note that for negative values of N the result will almost certainly be incorrect.

    The formula:

    #define ROUND_UP(N, S) ((((N) + (S) - 1) / (S)) * (S))
    

    Makes use of the fact that integer division rounds down for non-negative integers and uses the S - 1 part to force it to round up instead.

    However, integer division rounds towards zero (C99, Section 6.5.5. Multiplicative operators, item 6). For negative N, the correct way to 'round up' is: 'N / S', nothing more, nothing less.

    It gets even more involved if S is also allowed to be a negative value, but let's not even go there... (see: How can I ensure that a division of integers is always rounded up? for a more detailed discussion of various wrong and one or two right solutions)

提交回复
热议问题