c - 以下代码片段的输出是什么?为什么?

标签 c

以下代码片段的输出是什么?为什么?

#include<stdio.h>

void main(){
printf("Before while");
while(1);
printf("After while");
}

最佳答案

如果您只是花精力编译和运行,您可能什么也看不到。

那是因为:

  1. 即使您打印 Before while,您也不会在末尾发送换行符。由于标准输出通常是交互式设备的行缓冲(a),因此它应该缓存它,直到您发送换行符、刷新流或退出程序。

  2. 不做这些事情,因为while(1);(注意分号)是一个无限循环,在其主体中不执行任何操作,这意味着它永远不会到达第二个 printf

<小时/>

(a) 如果您对此行为感兴趣,基本上有三种输出缓冲策略。

  • 无缓冲意味着输出直接传递;
  • 行缓冲意味着输出被缓存,直到输出换行符(尽管如果缓冲区已满,也可能在没有换行符的情况下输出);
  • 完全缓冲意味着输出会被缓存,直到缓冲区已满,此时输出且缓冲区重新启动。

ISO C 标准 (C11 7.21.3 Files/7) 中针对三个标准流的规则是:

At program startup, three text streams are predefined and need not be opened explicitly - standard input (for reading conventional input), standard output (for writing conventional output), and standard error (for writing diagnostic output).

As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

关于c - 以下代码片段的输出是什么?为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59784030/

相关文章:

c - STM32 : FatFs Library - f_mount

c - 读入输入,然后读入c编程中的每个字符

c++ - 从 native C/C++ 生成并运行 LLVM 代码

c - 如何在 C 中第二次执行函数时将 printf 打印到下一行?

c - token to unsigned printing odd 值

c - 如何在C中将节点添加到二叉树?

c - "Parse error before "] "token"分配给变量[]时

c - 为什么下面会打印它的作用?

C - 初始化元素不是常量

c - 如何在c中打印指针?