Hey all
I have some trouble understanding the old goto.c ( see also goto man page V6 Thompson Shell Port - Manuals - GOTO(1) ) from this source code:
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67 |
int offset 0;
main(argc, argv)
char *argv[];
{
extern fin;
char line[64];
if (argc<2 || ttyn(0)!='x') {
write(1, "goto error\n", 11);
seek(0, 0, 2);
return;
}
seek(0, 0, 0);
fin = dup(0);
loop:
if (getlin(line)) {
write(1, "label not found\n", 16);
return;
}
if (compar(line, argv[1])) goto loop;
seek(0, offset, 0);
}
getlin(s)
char s[];
{
int ch, i;
i = 0;
l:
if ((ch=getc())=='\0') return(1);
if (ch!=':') {
while(ch!='\n' && ch!='\0')
ch = getc();
goto l;
}
while ((ch=getc())==' ');
while (ch!=' ' && ch!='\n' && ch!='\0') {
s[i++] = ch;
ch = getc();
}
while(ch != '\n')
ch = getc();
s[i] = '\0';
return(0);
}
compar(s1, s2)
char s1[], s2[];
{
int c, i;
i = 0;
l:
if(s1[i] != s2[i]) return(1);
if (s1[i++] == '\0') return(0);
goto l;
}
getc()
{
offset++;
return(getchar());
} |
Line 1-17: Everything ok.
My problem starts with getlin(line).
I try to comment as far as I understood:
Code:
getlin(s)
char s[];
{
int ch, i;
i = 0;
l:
// if we reach the end of the script, we return with 1
if ((ch=getc())=='\0') return(1);
//If the first char is not a ':' we iterate char by char thorugh the whole line
//we goto l and check the next line for a starting ':'
if (ch!=':') {
while(ch!='\n' && ch!='\0')
ch = getc();
goto l;
}
// there is a ':' as the first char in a line found
// we skip all the spaces in front of the label
while ((ch=getc())==' ');
// Now we copy just the label to s
while (ch!=' ' && ch!='\n' && ch!='\0') {
s[i++] = ch;
ch = getc();
}
// Question 1
while(ch != '\n')
ch = getc();
s[i] = '\0';
// Question 2
return(0);
}
@Question 1
Why would you do this while loop?
What would happen if we don't run this loop?
@Question 2
Why do we return with 0? We found a line, which starts with ':' and a label.
If we return 0, we would go into
Code:
if (getlin(line)) {
write(1, "label not found\n", 16);
return;
}
altough we did find a label.
I hope you can help me