why does $1 in yacc/bison has a value of 0 -
i have following production in bison spec:
op : '+' { printf("%d %d %c\n", $1, '+', '+'); } when input + following output:
0 43 + can explain why $1 has value of 0, shouldn't 43? missing?
edit
there no flex file, can provide bison grammar:
%{ #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", $1, '+', '+'); } | '-' { printf("%d %d %c\n", $1, '-', '-'); } | '*' { printf("%d %d %c\n", $1, '*', '*'); } ; 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 parse stop */ if (c == '\n') return 0; return (c); } int yyerror(char * s) { fprintf(stderr, "%s\n", s); return 0; } /* allows printing of error message */
$1 semantic value of first symbol on right-hand side, in case '+'. since terminal, semantic value whatever value of yylval when scanner returned '+' token parser.
since scanner not set yylval in case returns '+' (which totally normal), use of $1 in production not defined. normally, grammar doesn't reference semantic values of tokens '+', purely syntactic , don't have semantic values.
however, since yylval static variable, have been initialized 0, continue have value until set (for example, while scanning number).