为什么 yacc/bison 中的 $1 的值为 0

why does $1 in yacc/bison has a value of 0

我在 bison 规范中有以下作品:

op : '+' { printf("%d %d %c\n", , '+', '+'); }

当我输入 + 时,我得到以下输出:

0 43 +

有人能解释一下为什么 </code> 的值为 0,不应该是 43 吗?我错过了什么?</p> <p><strong>编辑</strong></p> <p>没有flex文件,但我可以提供一个<code>bison语法:

%{
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int yylex();
int yyerror();

%}

%token NUMBER

%%

lexp : NUMBER 
     | '(' op lexp-seq ')'
     ;
op : '+' { printf("%d %d %c\n", , '+', '+'); }
   | '-' { printf("%d %d %c\n", , '-', '-'); }
   | '*' { printf("%d %d %c\n", , '*', '*'); }
   ;

lexp-seq : lexp-seq lexp
         | lexp
         ;

%%

int main(int argc, char** argv) {
  if (2 == argc && (0 == strcmp("-g", argv[1])))
    yydebug = 1;

  return yyparse();
}

int yylex() {
  int c;

  /* eliminate blanks*/
  while((c = getchar()) == ' ');

  if (isdigit(c)) {
    ungetc(c, stdin);
    scanf("%d", &yylval);
    return (NUMBER);
  }

  /* makes the parse stop */
  if (c == '\n') return 0;

  return (c);
}

int yyerror(char * s) {
  fprintf(stderr, "%s\n", s);
  return 0;
} /* allows for printing of an error message */

</code> 是右侧第一个符号的语义值,在本例中为 <code>'+'。因为这是一个终端,它的语义值将是扫描器向解析器返回 '+' 标记时 yylval 的值。

由于您的扫描仪在 returns '+' 的情况下未设置 yylval (这是完全正常的),因此在该产品中使用 </code>没有明确定义。通常,文法不会引用像 <code>'+' 这样的标记的语义值,它们是纯句法的,没有语义值。

然而,由于 yylval 是一个静态变量,它会被初始化为 0,因此它将继续具有该值直到它被设置(例如,扫描 NUMBER ).