Question

In K&R, at the beginning of chapter 5, is presented the function getint that

performs free-format input conversion by breaking a stream of charachters into integer values, one integer per call.

The function is pretty simple, but i can't actually understand why is c pushed back in to the buffer in the first if-statement. Because of this, every time you call getint it will do the same thing. Because it will read the next charachter in the buffer, which is c. Is this strategy intended to be a kind of security mechanism?

int getint(int *pn) {
    int c, sign;
    while(isspace(c = getch()))
        ;
    if(!isdigit(c) && c != EOF && c != '+' && c != '-') {
        ungetch(c);
        return 0;
    }

    sign = (c == '-') ? -1 : 1;
    if(c == '+' || c == '-')
        c = getch();

    for(*pn = 0; isdigit(c); (c = getch()))
        *pn = 10 * *pn + (c - '0');
    *pn *= sign;
    if(c != EOF)
        ungetch(c);
    return c;

}
Was it helpful?

Solution

The code you ask about causes getint to stop if the next character in the stream is not part of a numeral (or a space) because it is not a digit or sign character.

The notion is that as long as you call getint while there are acceptable numerals in the input, it will convert those numerals to int values and return them. When you call getint while there is not an acceptable numeral next in the input, it will not perform a conversion. Since it is not performing a character, it leaves the character it is not using in the stream.

A proper routine would return an error indication so the caller can easily determine that getint is not performing a conversion for this reason. As it is, the caller cannot distinguish between getint returning 0 for a “0” in the input and getint returning 0 for a non-numeral in the input. However, as this is only tutorial code, features like this are omitted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top