an example from a book:
#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("lines: %d\nwords: %d\ncharacters: %d", nl, nw, nc);
}
suppose the input was stack overflow
. here is my understanding of how this code will function:
1.getchar()
will take s
from the buffer, so c = 's'
, and add 1 to nc
.
2.check if c
is \n
. if true, add 1 to nl
.
3.check if c
is a blank, a newline, or a tab. if true, state is 0.
4.'else if' state
is 0, state
is 1 and add 1 to nw.
my question is: in step 4, why is else if
necessary? even without else
, state
should still be checked if 0
, no? will the rest of the while
body be skipped if one of the if
checks are true? how do theses loops behave exactly?
Aucun commentaire:
Enregistrer un commentaire