简单表达式翻译器

构造一个中缀表达式到后缀表达式的翻译器,初步了解递归下降语法分析原理及语法制导翻译的过程。包含+,-,*,/,()

expr ------> expr + term                {print(‘+’)} 

    | expr - term                  {print(‘-’)}

             | term

term ----->  term * factor                   {print(‘*’)}

          | term / factor               {print(‘/’)}

                  | factor

factor ----> (  expr  )

                | id                                        {print(id.lexeme)}            

         | num                                  {print(num.value)}



点击(此处)折叠或打开

  1. #include<stdio.h>
  2. #include<ctype.h>
  3. void expr();
  4. int lookahead;
  5. void match(int t)
  6. {
  7.     if (lookahead == t)
  8.         lookahead = getchar();
  9.     else {
  10.         printf("syntax error!");
  11.         return;
  12.     }
  13. }
  14. void factor()
  15. {
  16.     if (isdigit(lookahead)){
  17.         printf("%c",lookahead);match(lookahead);
  18.     }else if(lookahead == '('){
  19.         match('(');expr();match(')');
  20.     }else if((lookahead >='a'&&lookahead <='z')||(lookahead >='A'&&lookahead <='Z')){
  21.         printf("%c",lookahead);match(lookahead);factor();
  22.     }
  23. }

  24. void term()
  25. {
  26.     factor();
  27.     while(1){
  28.         if(lookahead == '*'){
  29.             match('*');factor();printf("*");
  30.         }else if( lookahead == '/'){
  31.             match('/');factor();printf("/");
  32.         }else return;
  33.     }
  34. }
  35. void expr(){
  36.     term();
  37.     while(1){
  38.         if(lookahead == '+'){
  39.             match('+');term();printf("+");
  40.         }else if(lookahead == '-'){
  41.             match('-');term();printf("-");
  42.         }
  43.         else return;
  44.     }
  45. }
  46. int main(){
  47.     lookahead = getchar();
  48.     expr();
  49.     printf("\n");
  50.     getchar();
  51.     return 0;
  52. }

1.         实验采用递归下降方法,可识别单字符的factor ,未添加下划线等其余变量标识符。

2.         若在factor()函数中递归调用factor()函数,可识别多字符的factor,但识别效果可能会造成二义性,建议加入分割符。

       3.         递归调用 factor()在原理上有待商榷,它将多字符 id分割成多个 factor,在形成词法单元时可能出错。


<script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/buttonLite.js#style=-1&uuid=&pophcol=3&lang=zh"></script> <script type=text/javascript charset=utf-8 src="http://static.bshare.cn/b/bshareC0.js"></script>
阅读(91) | 评论(0) | 转发(0) |
0

上一篇:图片抓取

下一篇:Java生成API

给主人留下些什么吧!~~
评论热议
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值