Skip to content
C project #23Advanced

Expression Evaluator

A small calculator language: lexer, shunting-yard conversion to RPN, a stack machine, variables, functions and precise error messages.

Estimated time
~12 hours to build
Files
9 files · 498 lines
Technologies
C11, <math.h>

Introduction

Compilers and interpreters start with the same steps: break text into tokens, understand precedence and evaluate. This project builds a complete pipeline for arithmetic expressions — a compact introduction to compiler design.

Problem statement

Evaluate expressions with + − * / % ^, unary minus, parentheses, variables (let x = …), the functions sqrt, abs, min, max and pow and the constant pi. Respect precedence and associativity (^ is right-associative), show the RPN form on request, and report errors such as unmatched parentheses, unknown variables, missing operands and division by zero with useful messages.

Objectives

  • Write a lexer that produces typed tokens with positions
  • Implement Dijkstra's shunting-yard algorithm
  • Evaluate postfix expressions with a stack
  • Distinguish unary and binary minus

Features

  • Correct precedence and associativity
  • Unary minus
  • Variables and functions with arity checks
  • :rpn to show postfix form, :vars to list variables
  • Column-accurate error messages

Concepts demonstrated

  • Lexical analysis
  • Operator precedence parsing
  • Stack machines
  • Error handling

System architecture

lexer.c turns the input into Tokens (number, identifier, operator, parentheses, comma). eval.c converts the token list to RPN with an operator stack, using the previous token to decide whether - is unary, and then evaluates the RPN with a value stack, applying functions by arity. main.c handles let, commands and printing.

TextArchitecture diagram
"2 + 3 * 4" ─lexer─> [2][+][3][*][4] ─shunting-yard─> 2 3 4 * + ─stack VM─> 14

Folder structure

TextProject tree
expression-evaluator/
├── README.md
├── Makefile
├── src/eval.c
├── src/eval.h
├── src/lexer.c
├── src/lexer.h
├── src/main.c
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

Makefile

20 lines
MakefileMakefile
# Generated for KENHOLT Skills. Usage: make | make test | make clean
CC = gcc
CFLAGS = -std=c11 -Wall -Wextra -O2
SRC := $(wildcard src/*.c)
HDR := $(wildcard src/*.h)
ARGS := $(shell cat tests/args.txt 2>/dev/null)
INPUT := $(wildcard tests/sample-input.txt)
app: $(SRC) $(HDR)
$(CC) $(CFLAGS) -Isrc $(SRC) -o app -lm
test: app
./app $(ARGS) $(if $(INPUT),< $(INPUT),) > actual.txt
diff actual.txt tests/expected-output.txt && echo "Test passed: output matches tests/expected-output.txt"
clean:
rm -f app app.exe actual.txt
.PHONY: test clean

What each file does

src/lexer.h
Token types and the tokenizer API.
src/lexer.c
Character-level scanning into tokens.
src/eval.h
The evaluator API and variable functions.
src/eval.c
Variables, shunting-yard conversion, RPN evaluation and function calls.
src/main.c
The REPL, let assignments and commands.
Makefile
Build automation: make builds ./app, make test runs the sample session and compares it with the expected output, make clean removes build files.

How to run it

Build

Terminal
gcc -std=c11 -Wall -Wextra -Isrc src/*.c -o app -lm
# or simply: make

Run

Terminal
./app # Linux / macOS
.\app.exe # Windows

Test against the expected output

Terminal
./app < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt # no output means they match
# Windows PowerShell:
# Get-Content tests\sample-input.txt | .\app.exe > actual.txt
# Compare-Object (Get-Content actual.txt) (Get-Content tests\expected-output.txt)

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Expression evaluator - :vars, :rpn EXPR, :quit
> 2 + 3 * 4
= 14
> (2 + 3) * 4
= 20
> 2 ^ 3 ^ 2
= 512
> -3 ^ 2
= -9
> 10 % 4 + 7 / 2
= 5.5
> let r = 2.5
r = 2.5
> pi * r ^ 2
= 19.63495408
> :rpn (1 + 2) * -3
rpn: 1 2 + 3 neg *
= -9
> max(4, sqrt(81)) + min(2, abs(-7))
= 11
> let total = r * 4
total = 10
> :vars
r = 2.5
total = 10
> 1 / (3 - 3)
error: division by zero
> 2 * (3 + 4
error: unmatched '('
> x + 1
error: unknown variable 'x'
> 4 + * 2
error: missing operand before '*' at column 5
> let 9x = 1
error: use let NAME = EXPRESSION
> :quit
bye
Input
2 + 3 * 4
(2 + 3) * 4
2 ^ 3 ^ 2
-3 ^ 2
10 % 4 + 7 / 2
let r = 2.5
pi * r ^ 2
:rpn (1 + 2) * -3
max(4, sqrt(81)) + min(2, abs(-7))
let total = r * 4
:vars
1 / (3 - 3)
2 * (3 + 4
x + 1
4 + * 2
let 9x = 1
:quit

Testing

  • Diff with tests/expected-output.txt.
  • Check precedence: 2 ^ 3 ^ 2 = 512 (right-associative) and -3 ^ 2 = -9.
  • Feed malformed input such as 4 + * 2 and 2 * (3 + 4 and read the error messages.

Common errors

-3 ^ 2 gives 9

Unary minus must have lower precedence than ^ (as in mathematics), so the power is applied first.

Function results wrong when nested

Push function names on the operator stack and pop them to the output when their closing parenthesis is reached.

Possible improvements

  • Comparison and logical operators
  • User-defined functions
  • Integer and fraction modes

Additional challenges

  1. 1Build an abstract syntax tree instead of RPN and print it.
  2. 2Add implicit multiplication (2pi, 3(4+5)).
  3. 3Compile expressions to a tiny bytecode and run it in a loop.

Built and tested it yourself? Mark it to update your dashboard.