变量参数库宏在stdarg.h中

时间:2014-08-31 10:32:58

标签: c arguments

我遇到了一个有竞争力的问题,询问以下内容的输出(请忽略问题的软件工程问题,如果有的话,因为这是一个学术性的例子,但如果它与问题相关,请详细说明):

#include <stdarg.h>
#include <stdio.h>
int ripple(int, ...);
int main()
{
    int num;
    num = ripple(3,5,7); // Shouldn't he pass 3 args after `3`, if arg count is 3?
    printf("%d", num);
    return 0;
}
int ripple(int n, ...)
{
    int i, j=1, k=0;
    va_list p;
    va_start(p, n);
    for(; j<n; ++j)
    {
        i = va_arg(p, int);
        for(;i;i&=i-1)// Didn't understand the usage
            ++k;
    }
    return k;
}

我真的没有知道这段代码是如何工作的或它的作用(也许是因为我对stdarg.h的经验接近于零)。我们非常欢迎任何帮助。 感谢。

1 个答案:

答案 0 :(得分:1)

j1中从n-1运行到ripple(),因此第一个参数就是ripple(3, 5, 7) 函数实际上是一加剩余参数的数量,和 调用for(;i;i&=i-1)// Didn't understand the usage ++k; 很好。

k

i的二进制表示中添加{{1} 位设置数,比较 "Counting bits set, Brian Kernighan's way""Bit Twiddling Hacks"中, 或者这个答案:https://stackoverflow.com/a/109036/1187415

因此,在您的情况下,5 = 101b7 = 111b总共设置了2 + 3 = 5位 ripple(3, 5, 7) = 5