我目前在1.5.1章节“文件复制”中,并编写了以下程序:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
如果我像这样运行它:
PS <..loc..> cc copy-0.c
PS ./a
Black
Black
White
White
Gray
Gray
输出即是输入。
这是我为实验目的编写的程序:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
printf("%c",c);
c = getchar();
}
}
它们产生相同的结果,但是putchar
和printf
之间有什么区别呢?
在这两者之间,哪一个更好用呢?
printf("%c, c);
和putchar(c);
的行为是相同的。 - M.Mprintf("%c, c)
和putchar(c)
函数除了返回值不同外,其它方面是相同的——在这个例子中没有使用返回值。putchar(c)
比printf("%c, c)
执行速度更快。速度差异的程度高度依赖于许多其他因素。 - chux - Reinstate Monicaprintf("%c, c)
和putchar(c)
发出相同的代码,因此在这种情况下没有性能差异。对于不太智能的编译器,putchar(c)
由于其简单功能肯定比printf("%c, c)
更快,尽管在没有测试的情况下,速度差异的程度是未知的,可能是微不足道的。putchar_unlocked()
不是标准 C 库函数 - 我不熟悉它的细节。 - chux - Reinstate Monica