以下代码片段的输出是什么?为什么?
#include<stdio.h>
void main(){
printf("Before while");
while(1);
printf("After while");
}
最佳答案
如果您只是花精力编译和运行,您可能什么也看不到。
那是因为:
即使您打印
Before while
,您也不会在末尾发送换行符。由于标准输出通常是交互式设备的行缓冲(a),因此它应该缓存它,直到您发送换行符、刷新流或退出程序。您不做这些事情,因为
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/