函数 returns int 但出现奇怪的行为

Function returns int but getting strange behavior

我写了一些代码来计算一个字中的位数。当我 printf() 计数时,它按预期打印 32,但是当我将相同的代码插入函数并打印 return 值时,它给了我一些疯狂的大数字。

然后我 copy/pasted 代码返回到 main() 打印计数并同时打印我的函数的 return 值,嘿,两个都给了我 32 但如果我然后注释掉 main() 中的代码,我的函数再次打印大数字。

有人知道为什么会这样吗?

#include <stdio.h>

int wordlength();

int main() {

printf("%d", wordlength()); // prints 4195424 but
                          // if I uncomment the code below
                          // it then prints 32 like I want

//  int count;
//  unsigned int n = ~0;
// 
//  while( n != 0) {
//      n = n >> 1;
//      count++;
//  }
//  printf("\n%d", count); // prints 32 as expected

    return 0;
}

int wordlength() {

    int count;
    unsigned int n = ~0;

    while( n != 0) {
        n = n >> 1;
        count++;
    }

    return count;
}

您必须将 count 初始化为 0 或其他值,否则它将具有未定义的值。

在您的 wordlength() 函数中,count 是一个自动局部作用域变量,未明确初始化。所以,初始值是不确定的。

引用C11标准,章节§6.7.9

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]

您很容易对其应用 post-增量。它调用 undefined behavior.

相关,附件 §J.2,未定义行为的原因,

The value of an object with automatic storage duration is used while it is indeterminate.

所以,您的程序展示了 UB,根本不能保证产生任何有效结果。

解决方案:将count初始化为0。

FWIW,关于评论

// if I uncomment the code below
// it then prints 32 like I want

也是UB的结果