Search code examples
ckernighan-and-ritchie

Difficulties with an example 1.9 of The C Programming Language


I'm am working my way through the exercises of the first chapter of The C Programming Language and while I understand most of what is said and shown, there is one example that I don't understand.

In 1.9, there is a function shown to return the length of a line while setting a char array, passed as an argument, to the contents.

int get_line(char s[], int lim)
{
    int c, i, l;

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

    return l;
}

The thing I do not understand, is why we need this: if (c == '\n') {...}. Could this not be combined in the for-loop? Where we explicitly check that c is not equal to '\n'? I'm having trouble wrapping my head around why this needs to be an external condition.

Any light shed would be helpful! Thanks!


Solution

  • If you want to put it in the loop, you have to do something like that:

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

    So as you see, wrapping the condition inside the loop, led to more conditions checks and a break statatement.