Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

K&R C Exercise 4-11, Static Variables

Tags:

c

So I've been going through the K&R book the past few weeks. I've done it all in order, haven't really skipped much. If I get stuck on something I can usually google the example and find an answer, but this time, I've been stumped.

Section 4.6 deals with declaring static variables, both externally and internally. The exercise says this:

Exercise 4-11. Modify getop so that it doesn't need to use ungetch. Hint: use an internal static variable.

This has to do with a Polish calculator. getop collects the next operator or operand, and ungetch pushes a character back onto the input stack.

The original function looks like this:

int getop(char s[])
{
int i, c;

while ((s[0] = c = getch()) == ' ' || c == '\t')
    ;

s[1] = '\0';    
if (!isdigit(c) && c != '.' && c != '-' )
    return c;       /* not a number */          
i = 0;
if (c == '-') {
    if (isdigit(c = getchar())) {
        s[i] = '-';
        ungetch(c);
    }
    else {
        ungetch(c);
        return '-';
    }
}

if (isdigit(c))     /* collect integer part */
    while (isdigit(s[++i] = c = getch()))
    ;

if (c == '.')       /* collect a fraction part */
    while (isdigit(s[++i] = c = getch()))
    ;

s[i] = '\0';

if (c != EOF)
    ungetch(c);

return NUMBER;
}

Most examples I've looked up look like this:

static int buf = EOF;

if (buf != EOF && buf != ' ' && buf != '\t'
    && !isdigit(buf) && buf != '.') {
    c = buf;
    buf = EOF;
    return c;
}
if (buf == EOF || buf == ' ' || buf == '\t') 
    while ((*s = c = getch()) == ' ' || c == '\t')
        ;
else 
    *s = c = buf;
buf = EOF;

My problem is that doesn't take into account the modification we were supposed to make to getop earlier, which was to handle negative numbers. None of the examples I've found also seem to make any use of the fact that the variable is static, and therefore stays around after the function is called. We just set it to EOF at the end. If it doesn't matter what the variable is between function calls, why use a static variable?

Finally, I'm not sure how to use the static variable to stick c back onto the input stack. getch uses a shared array between getch and ungetch that getop has no awareness of.

Sorry for the longer post for such a simple example.

like image 532
Austin Brown Avatar asked Nov 19 '25 04:11

Austin Brown


1 Answers

The basic idea is that anywhere in getop that you currently have ungetch(), you instead set your static variable to the value you'd be un-getting. Then, everywhere you call getch(), you'd get the value from the static variable instead if it's valid (you may need a second static variable to say whether it's valid, which you clear when you read it, and set when you un-get into it).

like image 200
Jerry Coffin Avatar answered Nov 20 '25 17:11

Jerry Coffin