1

我正在使用 BISON 和 FLEX。如果我发布了 kcalc.l 文件,return 0 会做什么?而且我没有使用没有主体的 yywrap (我的意思不是字面意思,而是一个空的主体)。代码是一个计算器,没有任何变量管理和基本操作,可以完成,如加减乘除和一元减号处理操作员。我一直在研究 lex 和 yacc 规范,但没有得到我提出的查询的任何答案。

   Kcal.y

%{
   #include <stdio.h>
%}
%token  Number
%left '-' '+'
%left '*' '/'
%nonassoc UMINUS
%%
    statement:  expression
                 { printf(" result = %d\n", $1);} ;
    expression: expression '+' expression
                 { $$ = $1 + $3;
                   printf("Recognised'+'expression\n");
                  }
               |   expression '-' expression
                  { $$ = $1 - $3;
                    printf("Recognised '-' expression\n");
                  }
               |    expression '*' expression
                  { $$ = $1 * $3;
                    printf("Recognised '*' expression\n");
                  }
               |    expression '/' expression
                  { if ($3 == 0)
                    printf ("divide by zero\n");
                    else 
                     $$ = $1 / $3;
                     printf("Recognised '/' expression\n");
                  }
               | '-' expression %prec UMINUS
                         {
                             $$ = - $2;
                             printf("Recognised paranthesized expression\n");
                          }
               | '(' expression ')' 
                      { 
                           $$ = $2;
                           printf("Recognised paranthesized expression");
                       }
               | Number { $$ = $1;
                          printf("Recognised a no.\n");
                         }
          ;
%%
   int main(void)
   {
     return yyparse();
   }
    int yyerror (char *msg)
     {
       return fprintf(stderr,"Yacc :%s", msg);
      }
     yywrap()
        { 
         }
 
kcalc.l
%{
   #include "y.tab.h"
   extern int yylval;
%}
%%
[0-9]+ {  yylval = atoi(yytext);
          printf("accepted the number : %d\n", yylval);
          return Number; }
[ \t]   { printf("skipped whitespace \n");}
\n      { printf("reached end of line\n");
          **return 0;**
        }
.    { printf("found other data \" %s\n", yytext);
        return yytext[0];
     }
%%
4

1 回答 1

1

通知解析器的return 0输入结束,因此显然表达式应该包含在一行中。空的身体yywrap是错误的。如果您-Wallgcc编译器一起使用,它将给出两个警告yywrap

kcal.y:54: warning: return type defaults to ‘int’
kcal.y:55: warning: control reaches end of non-void function

第一个是因为没有指定函数的结果类型(K&R 风格 C),所以假设它应该返回一个int. 第二个警告是因为它缺少return这样一个int.

由于换行符终止输入,因此yywrap被调用的机会很小。但是如果输入不包含换行符,它将被调用。如果纯属意外(或多或少随机的)返回值yywrap被解释为0标记器将最终陷入重复调用的无限循环yywrap

于 2013-04-16T23:36:11.570 回答