c - 在 C 中使用未声明的标识符 'a'

标签 c bit-manipulation bit

<分区>

我一直收到一条错误消息“使用未声明的标识符‘a’”。据我所知,我已声明“a”等于 0,因此应该设置它。

int numOfBits(short num)
{
    for(int a = 0; num; num >> 1){
        a += num & 1;
    }
    return a;
}

最佳答案

这超出了范围。

int numOfBits(short num)
{
    // Requires C99 for loop variable declaration
    for(int a = 0; num; num >> 1) {   // `a` declared *inside* the
                                      // for loop block scope
        a += num & 1;
    }
    return a;                         // `a` is no longer in scope
}

只需将声明移出:

int numOfBits(short num)
{
    int a;
    for(a = 0; num; num >> 1) {
        a += num & 1;
    }
    return a;
}

关于c - 在 C 中使用未声明的标识符 'a',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46735468/

相关文章:

Php日历星期随机用户计算

c++ - 在 C/C++ 中签名扩展数字的最佳方法是什么

python ctypes,通过引用传递双指针

c - Linux 用户空间程序的正确构建环境

java - 位运算符 - 精度

c++ - 零位移位会正常工作吗?

c++ - C/C++ 中的位顺序

c - 在 C 中使用 static const unsigned long long int 变量分配 static const double

c - 在 C 中反转字符串不会输出反转的行

c++ - 编译器如何实现位域运算?