Mr Morgan
Mr Morgan

Reputation: 2243

What is happening in this C code when return is called?

This may seem a crass question but it is important. Can anyone tell me what is happening in this C code and what is the value of n when it returns?

MAX_BUFFER is set to 256. I am especially interested in variable n when it is returned.

int getinteger(void) {
    char buff[MAX_BUFFER];
    int i;
    int n;
    /* Strip leading comments and blank lines */
    do {
        fgets(buff, sizeof (buff), stdin);
        i = strspn(buff, " ");
    } while (buff[i] == '#' || buff[i] == '\n');
    if (sscanf(buff + i, "%d", &n) != 1) {
        fatal("Getinteger error (%s)", buff);
    }
    return n;
}

When called a value of -2 is returned. I do not understand why.

Upvotes: 0

Views: 82

Answers (1)

unwind
unwind

Reputation: 400159

The value of n will depend on the input.

It basically reads lines, until it finds one that doesn't start with # or is blank. Leading spaces are ignored, that's what the call to strspn() does.

Once such a non-empty line is found, it is expected to contain a decimal integer, which is converted (using sscanf() and stored in the local variable n) and returned. If the conversion fails, an error is printed.

Upvotes: 1

Related Questions