I'm interested in C so I want to explore more on C especially C89 to see how this language changed over the time :). I bought "The C programming language" (2nd edition) by Denis Ritchie.
An example in the book brings me to a complicated situation about the getchar() function.
Example 1 which is my example after reading the book is:
#include <stdio.h>
int main()
{
int c = getchar();
printf("\'\\n\' character in c: %d\n", c == '\n');
printf("\'\\n\' character in c: %d\n", c == '\n');
}
The output of example 1 is:
a
'\n' character in c: 0
'\n' character in c: 0
In this case, the output doesn't show any new lines character in this input. HOWEVER, another example I try is:
#include <stdio.h>
int main()
{
int c;
while ((c = getchar()) != EOF) {
printf("\'\\n\' character in c: %d\n", c == '\n');
}
}
and the output of the code is:
a
'\n' character in c: 0
'\n' character in c: 1
I don't understand why the second example duplicates the printf() function and how it could read the '\n' character when it enters the loop. Meanwhile, the first example doesn't show anything relating to the '\n' character
Take your second example, i.e.
while ((c = getchar()) != EOF) {
printf("\'\\n\' character in c: %d\n", c == '\n');
}
and unroll the loop. It will become:
c = getchar();
if (c == EOF) return 0;
printf("\'\\n\' character in c: %d\n", c == '\n');
c = getchar();
if (c == EOF) return 0;
printf("\'\\n\' character in c: %d\n", c == '\n');
c = getchar();
if (c == EOF) return 0;
printf("\'\\n\' character in c: %d\n", c == '\n');
... and so on ...
Now compare this to your first version and you see that the difference is that the second example makes a getchar
call between the printf
while the first example only has one getchar
call.
In other words - the first example only reads the character 'a'
while the second example first reads the 'a'
then reads the '\n'
and then reads .... (whatever you type next)