Function for the Scanner

Now comes a major change:

  • The code within the while loop is moved to a function named getToken.

  • All variables are now global, and there is an additional variable called token. This variable is overwritten every time something interesting is found in the input, such as being set to 1 for an integer, 2 for a plus, etc.

  • In main, getToken is called in a loop, and the value of token is printed. The loop exits when token has the value 7, indicating that getToken has encountered an EOF.

 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
@ <stdio.hdr>

global token: int = 0;
global ch: int = 0;
global val: int = 0;

fn getToken()
{
    if (ch >= '0' && ch <= '9') {
        val = 0;
        while (ch >= '0' && ch <= '9') {
            val = val * 10;
            val = val + ch - '0';
            ch = getchar();
        }
        printf("integer with value %d\n", val);
        token = 1;
    } else if (ch == '+') {
        printf("PLUS\n");
        ch = getchar();
        token = 2;
    } else if (ch == '*') {
        printf("ASTERISK\n");
        ch = getchar();
        token = 3;
    } else if (ch == ';') {
        printf("SEMICOLON\n");
        ch = getchar();
        token = 4;
    } else if (ch == '(') {
        printf("LPAREN\n");
        ch = getchar();
        token = 5;
    } else if (ch == ')') {
        printf("RPAREN\n");
        ch = getchar();
        token = 6;
    } else if (ch == EOF) {
        token = 7;
    } else {
        printf("ch = %d -> '%c'\n", ch, ch);
        ch = getchar();
        token = 8;
    }
}

fn main()
{
    while (true) {
        getToken();
        if (token == 7) {
            break;
        } else if (token == 1) {
            printf("token = %d, val = %d\n", token, val);
        } else {
            printf("token = %d\n", token);
        }
    }
}

Tasks

  • For now, let's not worry about the sense or nonsense of this change. First, let's practice our copy-and-paste skills and using our text editor. Don't copy and paste the above code, apply the changes manually.

  • Insert the following code after line 52:

    1
    2
    53         } else if (token == 1) {
    54             printf("token = %d, val = %d\n", token, val);
    
  • Remove all lines containing printf in getToken.