Ćazim Sinanagić
Ćazim Sinanagić

Reputation: 11

What exactly breaks the while loop in main?

What exactly breaks the while loop in this code? This is code from the book The C Programming Language from the C creators. It is a code from section 1.9. I guess int len will always be bigger than 0, but somehow when I compile this code the while loop breaks when I press Ctrl+Z (which is EOF for Windows).

#include <stdio.h>
#define MAXLINE 1000 /* maximum input line length */

int mgetline(char line[], int maxline);
void copy(char to[], char from[]);

/* print the longest input line */
main() {
    int len; /* current line length */
    int max; /* maximum length seen so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE]; /* longest line saved here */
    max = 0;
    while ((len = mgetline(line, MAXLINE)) > 0)
        if (len > max) {
            max = len;
            if (max == len)
                copy(longest, line);
        }
    if (max > 0) /* there was a line */
        printf("%s", longest);
    return 0;
}

/* mgetline: read a line into s, return length */
int mgetline(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;
        ++i;
    }
    s[i] = '\0';
    return i;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[]) {
    int i;
    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

Upvotes: 1

Views: 82

Answers (1)

Bathsheba
Bathsheba

Reputation: 234795

Loop 1: (In copy)

Strings in C are NUL-terminated by convention. NUL is a special char value with the value 0.

The value of the expression to[i] = from[i] is the new value of to[i].

That is 0 when NUL is reached, and the loop exits.

Loop 2: (In main)

Similarly the value of len = mgetline(line, MAXLINE) is the new value of len. That is 0 if mgetline returns 0 which is does when no characters are read. So that loop exits.

Upvotes: 3

Related Questions