fork download
  1. %{
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int yylex(void);
  6. void yyerror(const char *s);
  7. %}
  8.  
  9. %token NUM
  10. %left '+' '-'
  11. %left '*' '/'
  12.  
  13. %%
  14.  
  15. expr:
  16. expr '+' expr { printf("%d\n", $1 + $3); }
  17. | expr '-' expr { printf("%d\n", $1 - $3); }
  18. | expr '*' expr { printf("%d\n", $1 * $3); }
  19. | expr '/' expr {
  20. if ($3 == 0) {
  21. yyerror("Division by zero!");
  22. } else {
  23. printf("%d\n", $1 / $3);
  24. }
  25. }
  26. | '(' expr ')' { $$ = $2; }
  27. | NUM { $$ = $1; }
  28. ;
  29.  
  30. %%
  31.  
  32. void yyerror(const char *s) {
  33. fprintf(stderr, "Error: %s\n", s);
  34. }
  35.  
  36. int main() {
  37. printf("Enter an arithmetic expression:\n");
  38. yyparse();
  39. return 0;
  40. }
  41.  
Success #stdin #stdout #stderr 0.02s 6964KB
stdin
Hello World
stdout
Standard output is empty
stderr
ERROR: /home/f5MCrA/prog:40:1: Syntax error: Unexpected end of file
ERROR: '$runtoplevel'/0: Undefined procedure: program/0
   Exception: (3) program ? EOF: exit