该算术表达式的上下文无关文法是:
E -> E + T
| E - T
| T
T -> T * F
| T / F
| F
F -> num
| (E)
部分代码来自MOOC
#include <ctype.h> #include <stdio.h> #include <stdlib.h> void parse_F(); void parse_T(); void parse_E(); void error (char *want, char got); int i; char *str = 0; void error (char *want, char got) { fprintf (stderr, "Compling this expression: %s ", str); int j = i; while (j--) fprintf (stderr, " "); fprintf (stderr, "^ "); fprintf (stderr, "Syntax error at position: %d " " expecting: %s " " but got : %c ", i, want, got); exit (0); return; } void parse_F() { char c = str[i]; if (isdigit(c)){ i++; return; } if (c=='('){ i++; parse_E(); c = str[i]; if (c==')'){ i++; return; } error ("')'", c); return; } error ("'0-9' or '('", c); return; } void parse_T() { parse_F(); char c = str[i]; while (c=='*' || c =='/'){ i++; parse_F(); c = str[i]; } return; } void parse_E() { parse_T(); char c = str[i]; while (c=='+' || c == '-'){ i++; parse_T(); c = str[i]; } return; } void parse (char *e) { str = e; i = 0; parse_E(); if (str[i]=='