Yacc problem: Make data available in the next Non Terminal

I want to make some variables that I generated in b available in c:

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

      

Simple example:

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

      

so I can, later in c say:

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

      

Is there a chance to do this? Any help would be really appreciated!

0


source to share


2 answers


result

must be a global variable. You can do this by including

%{
    int result;
%}

      



at the top of your YACC file. Of course, you must also replace int result = 0

and int result = 1

with result = 0

and result = 1

respectively.

+1


source


You can do as suggested, however it is generally not recommended to use globals in syntax rules. Declare a type for b

and c

so that 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);};

      

0


source







All Articles