vendredi 14 septembre 2018

K&R 1.5.4, can anyone explain the else if in this code example?

I am painfully making my way through K&R 2nd ed. and I am not clear on what the final if (else if) is doing in example 1.5.4.

include stdio.h

define IN  1

define OUT 0

main()

{

        int c, nl, nw, nc, state;

        state = OUT;
        nl = nw = nc = 0;
        while ((c = getchar()) != EOF) {
            ++nc;
            if (c == '\n')
                ++nl;
            if (c == ' ' || c == '\n' || c == '\t')
                state = OUT;

            else if (state == OUT) {
                state = IN;
                ++nw;
        }
    }
    printf("%d %d %d\n", nl, nw, nc);
}

Does it mean: if state is OUT, then change state to IN, +1 to nw in any case

or

if state is OUT, do nothing, otherwise change state to IN, +1 to nw if state is IN

Comment in the text is: '[...] the [statement] after the else is an if that controls two statements in braces.'

For some reason I am having a hard time getting what is happening there. Can anyone help? I get a brain freeze every time I look at this.

Aucun commentaire:

Enregistrer un commentaire