【问题标题】:Ambiguous behavior of while() loop in cc中while()循环的模棱两可的行为
【发布时间】:2025-12-08 07:10:02
【问题描述】:

由于 while 循环因错误表达式而终止其执行,尽管下面给出了不同的输出。无法追踪

#include <stdio.h>
int main()
{
    //code snippet 1
    while(0){
        ;
    }
    printf("C");
    return 0;
}

这给出了输出

c

#include <stdio.h>
    int main()
    {
        //code snippet 2
        while(printf("%d")){
            ;
        }
        printf("c");
        return 0;
    }

这给出了输出

0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

由于 printf() 函数返回打印的字符数,并且没有打印任何字符,因此不应导致无限循环,因为 0 的逻辑值为 false。

【问题讨论】:

  • 它没有返回0。尝试运行printf("%d", printf("%d"));
  • 可以参考printf不带变量名的行为*.com/questions/437816/…
  • 依赖于输出编译器。我在 Windows 上使用 minGW
  • 谢谢,RishikeshRaje sshashank124,实际上它使用了一些垃圾值
  • 什么意思,没有打印字符?显然是一遍又一遍地打印字符0!您认为哪个电话正在打印0?打印c的不是第二个。

标签: c


【解决方案1】:

您的 printf("%d") 的返回值不是 0(实际上是未定义的行为)。
Printf with no arguments explanation

【讨论】: