C语言LL(1)语法分析程序示例,对包含四则运算和括号的表达式进行分析:
时间: 2024-05-13 11:16:58 浏览: 11
以下是一个简单的C语言LL(1)语法分析程序示例,可以对包含四则运算和括号的表达式进行分析。该示例使用递归下降法进行语法分析。
```c
#include <stdio.h>
#include <ctype.h>
int lookahead;
void expr();
void term();
void factor();
void error(const char* msg) {
printf("Error: %s\n", msg);
}
void match(int expected) {
if (lookahead == expected) {
lookahead = getchar();
} else {
char msg[100];
sprintf(msg, "Syntax error: expected %c but got %c", expected, lookahead);
error(msg);
}
}
void expr() {
term();
while (lookahead == '+' || lookahead == '-') {
match(lookahead);
term();
}
}
void term() {
factor();
while (lookahead == '*' || lookahead == '/') {
match(lookahead);
factor();
}
}
void factor() {
if (isdigit(lookahead)) {
match(lookahead);
} else if (lookahead == '(') {
match('(');
expr();
match(')');
} else {
error("Syntax error: expected digit or '('");
}
}
int main() {
printf("Enter an expression: ");
lookahead = getchar();
expr();
if (lookahead != '\n') {
error("Syntax error: unexpected input after expression");
}
return 0;
}
```
该程序中,`lookahead` 变量保存了当前读入的字符,`match()` 函数用于匹配当前字符并读入下一个字符。 `expr()`、`term()`、`factor()` 函数分别对应表达式、项、因子的语法规则,使用递归下降法进行语法分析。
该程序可以处理如下形式的表达式:
```
1+2*3
(1+2)*3
1/(2-3)
```
如果输入的表达式不符合语法规则,程序将输出错误信息。