VOOZH about

URL: https://www.geeksforgeeks.org/compiler-design/yacc-program-to-evaluate-a-given-arithmetic-expression/

⇱ Yacc Program to evaluate a given arithmetic expression - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Yacc Program to evaluate a given arithmetic expression

Last Updated : 11 Jul, 2025

Prerequisite - Introduction to YACC 
Problem: Write a YACC program to evaluate a given arithmetic expression consisting of '+', '-', '*', '/' including brackets.
Examples: 
 

Input: 7*(5-3)/2
Output: 7

Input: 6/((3-2)*(-5+2))
Output: -2 


Lexical Analyzer Source Code:
 

Parser Source Code:
 

Output:
 

👁 Image


Notes: 
Yacc programs are generally written in 2 files one for lex with .l extension(for tokenization and send the tokens to yacc) and another for yacc with .y extension (for grammar evaluation and result evaluation).
Steps for execution of Yacc program: 
 

yacc -d sample_yacc_program.y
lex sample_lex_program.l
cc lex.yy.c y.tab.c -ll
./a.out


 

Comment
Article Tags:

Explore