0

Lex file:

{Id}    {yylval.strVal=yytext; cout<<yytext<<endl; return Id;}

Yacc file:

%union{
int iVal;  
float fVal;  
char * strVal;
}; 

%token NS  
%token  <strVal>Id  
program : NS Id {cout<<$2;}

The Lex prints but the Yacc doesn't !!

ideas ppl ^_^

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Katia
  • 679
  • 2
  • 15
  • 42

2 Answers2

1

'yytext' is a static buffer that contains the current token. You are then passing a pointer into that buffer (as yylval) to the parser. This has the rather severe problem that if there are more tokens in your input, these later tokens may overwrite the same yytext buffer pointed at by an earlier token, so you will probably start seeing random garbage if you make your parser more complex. The trivial example here doesn't show this problem, as it doesn't try to read another token after seeing the 'Id' token.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • For a detailed explanation of how to avoid this static buffer issue to pass strings see the 2nd answer to this question https://stackoverflow.com/questions/1851829/how-to-use-yylval-with-strings-in-yacc/12549501#12549501 – JonN Apr 18 '18 at 01:01
  • @JonN: the problem with that general solution is that it tends to leak memory if you're not careful, and always leaks with syntax errors. Bison provides some help for the latter, but its still an ugly, tough problem. – Chris Dodd Apr 18 '18 at 19:04
0

To make the output appear in the Lex file, you'd add << endl between yytext and its following semi-colon. Otherwise, the output is buffered until a newline appears or the file is closed at the end of the program.

Your Lex code assigns to yylval.strVal, but your Yacc grammar doesn't define strVal as part of your %union. If the code is compiling, this indicates a disconnect somewhere in your use of headers. Your Lex code should be using the header generated by Yacc (yacc -d).


With the disconnect between the union resolved, and the confirmation that adding << endl to the Lex code showed that output, did you also think of adding << endl to the Yacc code? If not, do so! If you did, edit the code in the question to accurately reflect what you've got; we can't read your screen from this side of the Internet.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278