I am currently in chapter 1.5.1 File copying and made a program like so:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
}
If I ran it like this:
PS <..loc..> cc copy-0.c
PS ./a
Black
Black
White
White
Gray
Gray
The output is what I input.
And here's a program I made for experimental purposes:
#include <stdio.h>
/* copy input to output; 1st version */
main()
{
int c;
c = getchar();
while (c != EOF) {
printf("%c",c);
c = getchar();
}
}
It produces the same result but is there a difference between putchar
and printf
?
Which is better to use between the 2?
printf("%c, c);
andputchar(c);
have identical behaviour in this example. – Vassellprintf("%c, c)
andputchar(c)
function the same other than the return value differs - which is not used in this example.putchar(c)
will certainly perform faster thanprintf("%c, c)
. The degree of speed difference is highly dependent on many other factors. – Unmoorprintf("%c, c)
andputchar(c)
and so no performance difference in that case. With a less intelligent compiler,putchar(c)
, with its simple functionality would certainly be faster thanprintf("%c, c)
, although, without testing, the degree of speed difference is unknown and may be marginal.putchar_unlocked()
is not a standard C library function - I am unfamiliar with its details. – Unmoor