c - 函数返回 int 但出现奇怪的行为

标签 c function printf return-value

我写了一些代码来计算一个词中的位数。当我 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/

相关文章:

c - Accept() 如何确定返回哪个整数?

c - 尝试在 x64 RedHat 环境中编译 x86 C 程序 [第 2 部分]

java - 如何使用 printf() 和可变宽度使字符串输出居中?

java - 如何以右对齐方式打印数字?

c - "#include"C 程序中作为 char[] 的文本文件

c - 使用 XCB 的奇怪递归行为

php - 带有 % 百分比操作的嵌套 count() 函数

c - 如何定义此代码并将其作为函数调用?

javascript - 为什么 JavaScript 允许将数组和函数存储在一个变量中?

c - 如果仅尾随 0,则使用 printf 格式化没有小数位的 float