cheater cheater - 2 months ago 5
C Question

function to read a line on c programming language

On the C book, (second edition page 29), I read the following content:

/* getline: read a line into s, return length */

int getline(char s[], int lim)
int c, i;
for(i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
s[i] = c;
if(c == '\n') {
s[i] = c;
s[i] = '\0';
return i;


My question is: why it is
but not
in the for condition test? (ps: lim is the maximum length of a line)

Question 2: On C, is
counted as a character?

  1. Space needs to be reserved for the null-terminator \0 that is appended to the string at the end of the loop. (This is how strings are modelled in C).

  2. EOF is a special value that denotes the end of a file. Note how getchar() returns an int: this is chiefly so the value of EOF doesn't have to be within the range of a char.