Turner said:
Out of curiosity, why do programmers
insist that the following piece of code
printf("%d", 10);
is wrong and should be
printf("%d\n", 10);
The programmers you are listening to are wrong with one exception.
There is no reason not to use printf() to write partial lines. You can
use this to build up lines without complicated logic.
Consider a simple case, in which we print several lines of ints:
#include <stdio.h>
void example(void)
{
int i;
for (i = 0; i < 128; i++)
printf("%3d%c", i, (7 == i%8) ? '\n' : ' ');
}
This code has a trailing '\n' for only 1/8 of the lines. It can, of
course, have been written
#include <stdio.h>
void example(void)
{
int i;
for (i = 0; i < 128; i++) {
printf("%3d", i;
if (7 == i%8) putchar('\n');
else putchar(' ');
}
}
Now for the exception. It is implementation-defined what happens if you
do not terminate the last line of output with an end-of-line character.
It is not safe to leave out this last '\n' unless you are writing for a
particular environment and C implementation, you *know* what happens in
that environment and with that implementation, you *know* that neither
that environment nor implementation will ever change (via updates, etc.)
in its interpretation of leaving off that final '\n', and you *know*
that you will not need your program to ever run in any other configuration.
It's application specific, isn't it?
No.