我写了一些代码来计算一个词中的位数。当我 printf()
计数时,它按预期打印 32,但是当我将相同的代码插入函数并打印返回值时,它给了我一些疯狂的大数字。
然后我将代码复制/粘贴回 main()
打印计数并同时打印函数的返回值,嘿,它们都给了我 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;
}
最佳答案
在您的wordlength()
函数中,count
是一个自动的局部作用域变量,不会显式初始化。所以,初始值是不确定的。
引用C11
标准,章节§6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
您很容易对其应用后增量。它调用 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的结果。
关于c - 函数返回 int 但出现奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32775412/