The program from section 2.5

This is the source code for the program in section 2.5 of the course book, Aho, Sethi, Ullman: Compilers - Principles, Techniques, and Tools. I am using the original definitions of the functions expr and rest, without the optimizations on page 52-53. The code has been slightly modified to be valid, modern C (and also C++).

25.c

Download
/* The program from Aho, Sethi, Ullman section 2.5 */
/* Without the optimizations on page 52-53 */

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

int lookahead;

void error() {
  printf("syntax error\n");
  exit(EXIT_FAILURE);
}

void match(int t) {
  if (lookahead == t)
    lookahead = getchar();
  else
    error();
}

void term () {
  if (isdigit(lookahead)) {
    putchar(lookahead);
    match(lookahead);
  }
  else
    error();
}

void rest() {
  if (lookahead == '+') {
    match('+'); term(); putchar('+'); rest();
  }
  else if (lookahead == '-') {
    match('-'); term(); putchar('-'); rest();
  }
  else
  ;
}

void expr() {
  term(); rest();
}

int main(void) {
  lookahead = getchar();
  expr();
  putchar('\n');
  exit(0);
}


Thomas Padron-McCarthy (Thomas.Padron-McCarthy@tech.oru.se) January 2, 2003