Yacc Problem: Make Data available in next Non Terminal

♀尐吖头ヾ 提交于 2019-12-11 14:09:17

问题


I want to make some variables I generate in b available in c:

a   :   b c { ...some code...}

A simple example:

b :  X  { int result = 0; } 
  |  Y  { int result = 1; }

so I can, later on in c say:

c : D   { printf(result + 1); }
  | E   { printf(result + 2);  }

Is there any chance to do that? Any help would really be appreciated!


回答1:


result should be a global variable. You can do this by including

%{
    int result;
%}

at the top of your YACC file. Of course, you should also replace int result = 0 and int result = 1 with result = 0 and result = 1 respectively.




回答2:


You can do as Can suggested, however generally it is not a good idea to use globals in syntax rules. Declare a type for b and c so your rules look like this:

%union {
    int result;
};

%type <result> a b

%start a

%%

b : X {$$ = 0;} | Y {$$ = 1;} ;
c : D {$$ = 1;} | E {$$ = 2;} ;
a : b c {printf("%d", $1 + $2);};


来源:https://stackoverflow.com/questions/393041/yacc-problem-make-data-available-in-next-non-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!