Thread: K&R question

  1. #1
    Registered User
    Join Date
    Feb 2006
    Posts
    17

    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.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    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.

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    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"
    Sent from my iPadŽ

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. question about K&R example listing 1-6 Arrays
    By fsx in forum C Programming
    Replies: 1
    Last Post: 04-24-2009, 09:32 AM
  2. Question about K&R program
    By Aerie in forum C Programming
    Replies: 15
    Last Post: 04-24-2005, 07:09 AM
  3. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM