Skip to main content

Lesson 7 of 8

Mini Project Part 3 - Recursive Expression Evaluator

Build a recursive descent expression evaluator for arithmetic expressions like `3 + 5 * 2`. This project applies recursion, function decomposition, prototype ordering, and the call stack in a real algorithm. The grammar: `expr = term (('+' | '-') term)*`, `term = factor (('*' | '/') factor)*`, `factor = number | '(' expr ')'`.

16 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Recursive Calculator - Recursive Descent Parser

Recursive Calculator - Recursive Descent Parser
/* calc.c - recursive descent expression evaluator
   Handles: + - * / with correct precedence and parentheses    */

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

static const char *pos;   /* current position in input string */

/* Forward declarations (mutual recursion requires this) */
static double parse_expr(void);
static double parse_term(void);
static double parse_factor(void);

/* Skip whitespace */
static void skip_ws(void) {
    while (isspace((unsigned char)*pos)) pos++;
}

/* Parse a number or parenthesised sub-expression */
static double parse_factor(void) {
    skip_ws();
    if (*pos == '(') {
        pos++;              /* consume '(' */
        double val = parse_expr();
        skip_ws();
        if (*pos == ')') pos++;  /* consume ')' */
        return val;
    }
    /* Parse a number (integer or decimal) */
    char *end;
    double val = strtod(pos, &end);
    if (end == pos) {
        fprintf(stderr, "Error: expected number at '%s'
", pos);
        return 0.0;
    }
    pos = end;
    return val;
}

/* Parse term: handles * and / (higher precedence) */
static double parse_term(void) {
    double val = parse_factor();
    skip_ws();
    while (*pos == '*' || *pos == '/') {
        char op = *pos++;
        double right = parse_factor();
        if (op == '*') val *= right;
        else {
            if (right == 0.0) { fprintf(stderr, "Error: division by zero
"); return 0.0; }
            val /= right;
        }
        skip_ws();
    }
    return val;
}

/* Parse expr: handles + and - (lower precedence) */
static double parse_expr(void) {
    double val = parse_term();
    skip_ws();
    while (*pos == '+' || *pos == '-') {
        char op = *pos++;
        double right = parse_term();
        if (op == '+') val += right;
        else           val -= right;
        skip_ws();
    }
    return val;
}

double evaluate(const char *expr) {
    pos = expr;
    double result = parse_expr();
    return result;
}

int main(void) {
    const char *tests[] = {
        "3 + 5",
        "10 - 4 * 2",
        "( 10 - 4 ) * 2",
        "3.14 * 2 * 2",
        "100 / 4 / 5",
        NULL
    };

    for (int i = 0; tests[i] != NULL; i++) {
        printf("%-25s = %.4f
", tests[i], evaluate(tests[i]));
    }

    return 0;
}

/* Build: gcc -Wall -Wextra -std=c99 calc.c -o calc
   Output:
   3 + 5                     = 8.0000
   10 - 4 * 2                = 2.0000
   ( 10 - 4 ) * 2            = 12.0000
   3.14 * 2 * 2              = 12.5600
   100 / 4 / 5               = 5.0000                           */

Common Mistakes

  • Missing forward declarations for mutually-recursive functions - `parse_expr` calls `parse_term`, and `parse_term` calls `parse_factor`. Without prototypes at the top, the compiler sees `parse_term` called before its definition.
  • Not using `strtod` for number parsing - manual `sscanf` or custom loops are fragile. `strtod` handles signs, decimals, scientific notation, and gives you the end-pointer so you can advance `pos` correctly.
  • Using a global `pos` without thread safety awareness - this evaluator uses a static global `pos` pointer which is not reentrant. In multi-threaded code, use a struct to hold parser state and pass it by pointer.

Tip

Tip

Practice Mini Project Part 3 Recursive Expression Evaluator in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Recursive descent parsing mirrors mathematical operator precedence in call hierarchy

Practice Task

Note

Practice Task - (1) Write a working example of Mini Project Part 3 Recursive Expression Evaluator from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Mini Project Part 3 Recursive Expression Evaluator is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready c code.

Key Takeaways

  • Build a recursive descent expression evaluator for arithmetic expressions like `3 + 5 * 2`.
  • Missing forward declarations for mutually-recursive functions - `parse_expr` calls `parse_term`, and `parse_term` calls `parse_factor`. Without prototypes at the top, the compiler sees `parse_term` called before its definition.
  • Not using `strtod` for number parsing - manual `sscanf` or custom loops are fragile. `strtod` handles signs, decimals, scientific notation, and gives you the end-pointer so you can advance `pos` correctly.
  • Using a global `pos` without thread safety awareness - this evaluator uses a static global `pos` pointer which is not reentrant. In multi-threaded code, use a struct to hold parser state and pass it by pointer.

Topics in This Module

0/8 done