-
K&R question
I am reading the second edition of this great book and I have a question about a function that can be found on page 69. Here is the function:
Code:
int getline(char s[], int lim)
{
int c, i;
i = 0;
while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
s[i++] = c;
if (c == '\n')
s[i++] = c;
s[i] = '\0';
return i;
}
Why, instead of writing the code highlighted in red the authors did not just write something like this?
Code:
while (--lim > 0 && (c = getchar()) != EOF)
...
Thanks.
-
Because to get a line, you should stop at a newline. And if it way a newline, and was not EOF or limit, the newline is post-fixed to the buffer.
-
Because then the newline would be part of the s string and then it would keep looping. He wants the loop to stop at newlines. For instance, if I wrote:
"Hello World!\nHow are you?"
Without that line, the s string would read
"Hello World!\nHow are you?"
with it, after the if statement, it reads
"Hello World!\n"