这个C函数返回什么?

Ash*_*eyT -1 c return function

int f(int n)
{
    int i, c = 0;
    for (i=0; i < sizeof(int)*8; i++, n >>= 1)
        c = (n & 0x01)? c+1: c;
    return c;
}
Run Code Online (Sandbox Code Playgroud)

这是我在书上发现的练习,但我真的不明白!

Car*_*rum 7

它计算传入参数中设置的位数n(假设您的机器具有8位字节).我将使用您的代码进行内联评论(并修复可怕的格式):

int f(int n)
{
    int i;     // loop counter
    int c = 0; // initial count of set bits is 0

    // loop for sizeof(int) * 8 bits (probably 32), 
    // downshifting n by one each time through the loop
    for (i = 0; i < sizeof(int) * 8; i++, n >>= 1) 
    {
        // if the current LSB of 'n' is set, increment the counter 'c',
        // otherwise leave it the same
        c = (n & 0x01) ? (c + 1) : c;  
    }

    return c;  // return total number of set bits in parameter 'n'
}
Run Code Online (Sandbox Code Playgroud)