此为编译原理中一个小语法分析器的代码,此间获取单词类似gettoken()->type及下一个单词类型的getnext()->type.此间的-&g
#include<stdio.h>#define id 1
#define equal 2
#define add 3
typedef struct token_s
{
int type;
char name[64];
} token_t;
token_t token[100]= { {1, 'a'}, {2, '='},{1,'b'}, {3, '+' },{1,'b'}, {3, '+'},{1,'b'}};
int index=0;
token_t *gettoken()
{
return &token[index];
}
token_t *getnext()
{
index++;
return &token[index];
}
int match_S()
{
if(gettoken()->type==id&& getnext()->type == equal && match_A())
printf("grammar right.\n");
else printf("grammar wrong.\n");
}
int match_A()
{
if(getnext()->type==id && match_B())
return 1;
else
return 0;
}
int match_B()
{
if(getnext()->type == add)
if(match_A())
return 1;
else
return 0;
return 1;
}
int main()
{
int i;
for(i=0; i<100; i++){
if(token[i].type != 0)
printf("%s", token[i].name);
}
printf("\n");
match_S();
}