Skip to content
Tutorials Center
My learning

Topics

Lesson 110 of 135 ยท Projects

Project: Command Calculator

Build a command-line calculator in C - a tokenizer, a recursive descent parser with operator precedence, variables, math functions and clear error messages.

Type 2 + 3 * 4 into any calculator and it answers 14, not 20. It knows that multiplication binds tighter than addition, that parentheses override everything, and that 2 ^ 3 ^ 2 means 2 ^ 9. Teaching a program those rules is a classic exercise, because the same technique, parsing, sits inside every compiler, every spreadsheet formula engine, every configuration file reader and every command shell.

In this project you'll build a calculator that reads expressions from the Input box, one per line, and prints the results. It supports + - * / % ^, parentheses, unary minus, variables (radius = 2.5), math functions (sqrt(2)), an ans variable holding the last result, and commands like vars and quit. Above all, it never crashes on bad input: every mistake gets a clear message with a caret pointing at the exact spot.

You'll build it in three stages, and each stage is a complete program (every run starts fresh). The project brings together structures, enumerations, switch, recursion, function pointers, variadic functions, the math library and safe input with fgets.

The plan

A calculator has two separate jobs, and keeping them apart makes both simpler:

  1. Tokenizing (also called lexing): turning the characters 12.5*(x+1) into a list of meaningful pieces, or tokens: the number 12.5, a star, a left parenthesis, the name x, a plus, the number 1, a right parenthesis. Spaces disappear at this step.
  2. Parsing and evaluating: reading the tokens according to the rules of arithmetic and computing the value.

For the second job we'll use a recursive descent parser, the technique most hand-written parsers use (GCC's and Clang's C parsers are recursive descent too). The idea is to write the grammar as a set of rules, one per precedence level, and then turn each rule into one C function. Here's the grammar, from the lowest precedence to the highest. Braces { } mean "repeated zero or more times", and brackets [ ] mean "optional":

TEXT
expression := term { ('+' | '-') term }
term       := unary { ('*' | '/' | '%') unary }
unary      := ('-' | '+') unary | power
power      := primary [ '^' unary ]
primary    := number | name | name '(' expression ')' | '(' expression ')'

Read it from the bottom up. A primary is the smallest complete value: a number, a variable, a function call or a whole parenthesized expression. A power raises a primary to an exponent. A unary puts any number of signs in front. A term multiplies or divides unaries, and an expression adds or subtracts terms.

The precedence falls out of the structure. In 2 + 3 * 4, expression asks term for its first operand. term reads 2, sees +, which isn't its business, and returns. expression then sees the + and asks term for the right operand; term reads 3, sees *, and keeps going to multiply by 4 before returning 12. So the result is 2 + 12. The deeper a rule sits, the tighter its operators bind.

Level Operators Associativity Rule
Lowest + - left to right expression
* / % left to right term
unary - + right to left unary
Highest ^ right to left power

Two details are worth noticing. The { ... } loops in expression and term make those operators left-associative: 10 - 3 - 2 is (10 - 3) - 2 = 5. The power rule instead calls unary (which can lead back to power) for its right side, which makes ^ right-associative: 2 ^ 3 ^ 2 is 2 ^ (3 ^ 2) = 512, as in mathematics. And because unary sits above power, -2 ^ 2 means -(2 ^ 2) = -4, the convention used in math and in most programming languages that have a power operator.

Stage 1: the tokenizer

A token needs a kind (number, name, plus, ...), a value for numbers, the text for names, and the column where it starts so error messages can point at it. An enum lists the kinds and a struct holds one token:

C
typedef enum {
    TOK_NUMBER, TOK_NAME,
    TOK_PLUS, TOK_MINUS, TOK_STAR, TOK_SLASH, TOK_PERCENT, TOK_CARET,
    TOK_LPAREN, TOK_RPAREN, TOK_ASSIGN,
    TOK_END, TOK_ERROR
} token_kind;

next_token skips spaces and then looks at the next character:

  • A digit (or a dot followed by a digit) starts a number. Instead of collecting digits ourselves, we let strtod parse it: it handles 12, 4.5, .25 and 1.5e3 and tells us through its end pointer where the number stopped, which is exactly where the next token begins. See Converting Strings and Numbers.
  • A letter or underscore starts a name, which continues through letters, digits and underscores. Names are copied into a fixed-size array; anything past 31 characters is dropped rather than overflowing it.
  • One of + - * / % ^ ( ) = is a one-character operator, handled by a switch.
  • The end of the string produces TOK_END, and anything else is an error.

Note the (unsigned char) casts in the isdigit, isalpha and isspace calls. The <ctype.h> functions require a value that fits in unsigned char (or EOF), and on systems where char is signed, a byte like รฉ would be negative and cause undefined behavior. The Characters lesson explains why.

The main function reads one line at a time with fgets, removes the newline with strcspn, and prints every token. Because our input comes from the Input box and isn't echoed, the program prints each line after a > prompt so you can see what it's working on.

C Stage 1: a tokenizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The first three lines turn into tokens as expected, including 1.5e3 becoming 1500 and .25 becoming 0.25. The last line stops at the $, and the caret sits right under it: the column stored in each token pays off immediately. The printf("%*s^", column, "") trick prints an empty string padded to column characters, which is an easy way to print a run of spaces (see Printing Output for * widths).

Try your own lines in the Input box. Notice that the tokenizer doesn't care whether the tokens make sense: ) 3 ( + tokenizes happily. Deciding what's valid is the parser's job.

Stage 2: parsing and evaluating

The parser keeps the state of one line in a struct: the text, the tokenizer's position, the current token (the one we're deciding about) and error information.

C
typedef struct {
    const char *text;
    size_t pos;
    token current;
    bool failed;
    char message[96];
    size_t error_column;
} parser;

advance replaces current with the next token. Each grammar rule becomes a function that looks at current, consumes the tokens that belong to it, and returns the value of what it parsed. Compare parse_term with its grammar rule term := unary { ('*' | '/' | '%') unary }: it parses one unary, then loops for as long as the current token is one of its operators. parse_expression has the same shape one level up. parse_primary handles numbers and parentheses, and for ( expression ) it calls parse_expression recursively. That recursion is what lets parentheses nest to any depth: ((((1)))) simply goes four levels deep.

The functions call each other in a circle (parse_expression โ†’ parse_term โ†’ parse_unary โ†’ parse_power โ†’ parse_primary โ†’ parse_expression), so two of them are declared with prototypes before they're defined, as explained in Declarations, Prototypes and Headers.

Error handling without crashes

Bad input is normal for a calculator, so errors must be handled calmly. A simple and robust design:

  • fail records the first error only: a message (formatted with vsnprintf, so it works like printf) and the column.
  • It also sets current.kind to TOK_ERROR. No rule's loop continues on TOK_ERROR, and advance does nothing once the parser has failed, so every function quickly returns, unwinding the recursion naturally.
  • The value returned after a failure is meaningless, and the caller ignores it.

The alternative, setjmp/longjmp to jump straight out of deep recursion, is faster to write but much harder to reason about, especially once memory gets allocated along the way. A flag scales to bigger programs without surprises.

Division by zero is checked explicitly. With double, 4 / 0 wouldn't crash (it gives infinity under IEEE 754, as you saw in Floating-Point Numbers), but a calculator should say what went wrong. % uses fmod from <math.h>, so it works for non-integers too: 7.5 % 2 is 1.5.

Finally, after parse_expression returns, the current token must be TOK_END. If it isn't, there's junk after a complete expression, as in 3 4, which is reported as an error instead of being silently ignored.

C Stage 2: evaluating with precedence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check the results against the precedence table: 2 + 3 * 4 is 14, the parentheses make it 20, -2 ^ 2 is -4, and 2 ^ 3 ^ 2 is 512 (right-associative). 17 % 5 + 10 / 4 is 2 + 2.5 = 4.5, since all arithmetic is done in double. Then come four errors, each with its caret: a missing ) (the caret points at the end of the line, where the ) should be), a division by zero (pointing at the /), an extra number, and an expression that starts with an operator.

The results are printed with %.10g: up to ten significant digits, without trailing zeros, so 14 prints as 14 and 0.1 + 0.2 prints as 0.3 instead of exposing the tiny binary rounding error in 0.30000000000000004.

Stage 3: variables, functions and commands

The final stage turns the evaluator into a real tool. Three features need new code.

Variables. A variable_table holds up to 32 name/value pairs in an array of structs. find_variable searches it with strcmp, and set_variable updates an existing entry or appends a new one, reporting failure when the table is full. A linear search is perfectly fast for a few dozen variables; for thousands you'd use a hash table. The table starts with pi and e, and after every successful calculation the result is stored as ans.

In parse_primary, a TOK_NAME is either a function call (if a ( follows) or a variable lookup. Using a variable that was never assigned is an error, not a silent zero.

Assignments. A line like area = pi * radius ^ 2 starts with a name followed by =. Our parser looks at one token at a time, so run_line checks the first two tokens itself: if they're a name and =, it parses the rest as an expression and stores it. Otherwise it rewinds by restarting the parser on the same line and evaluates the whole line as an expression. Rewinding is cheap because the line is just a string in memory.

Functions. Math functions live in a table of structs, each holding a name and a function pointer:

C
typedef struct {
    const char *name;
    double (*apply)(double);
} math_function;

static const math_function functions[] = {
    {"sqrt", sqrt}, {"abs", fabs}, {"sin", sin}, {"cos", cos}, {"tan", tan},
    {"ln", log}, {"log10", log10}, {"exp", exp},
    {"floor", floor}, {"ceil", ceil}, {"round", round},
};

Adding a function is one line in the table; no parsing code changes. The table maps our friendlier names (abs, ln) to the <math.h> functions (fabs, log). This table-driven design is a pattern worth remembering: data replaces a long chain of if (strcmp(...)) branches.

A few more touches make it robust:

  • Results that aren't finite (sqrt(-4) is NaN, exp(1000) is infinity) are rejected with isfinite, rather than printing nan and storing it.
  • A line longer than the buffer is detected (no newline was read and we're not at the end of the input). The rest of the line is skipped with getchar and reported as an error, instead of being treated as a second line.
  • vars lists all variables, and quit or exit ends the program. Any input after quit is ignored.
C Stage 3: the complete calculator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Walk through the output. radius and area are assigned, and each assignment echoes its value. round(area * 100) / 100 rounds the area to two decimals: 19.63. The next line uses ans (that 19.63) and two functions to get 7.430575583. rate = 7 % is missing its right operand, so the caret points at the end of the line. floor(10 / 3) + cos(0) is 3 + 1 = 4. vars shows everything stored so far, including ans. price was never defined, 2 ^ 3 ^ 0 is 2 ^ 1 (right-associative again, so the line gives 3 - 2 = 1), sqrt(-4) is refused, and after quit the final 1 + 1 is never evaluated.

Tip: Paste in your own calculations, including deliberately broken ones: unbalanced parentheses, unknown functions, 2 ^, an empty pair (), a 300-character line. A good test of any parser is that no input, however strange, can crash it.

How the pieces fit together

Looking back, the program splits cleanly into layers, each knowing only about the one below it:

Layer Functions Knows about
Input main Lines, buffer limits, end of input
Statements run_line, print_variables Commands, assignments, ans
Grammar parse_expression ... parse_primary Tokens and precedence
Tokens next_token, advance Characters
Support fail, find_variable, set_variable, call_function Errors, the variable and function tables

That separation is what made each stage a small addition rather than a rewrite. In a larger program, each layer would be its own .c file with a header, as described in Multi-File Programs and Linkage.

Ideas to extend it

  • Multi-argument functions such as max(a, b) or pow(x, y): parse a comma-separated argument list and store an argument count in the function table.
  • Comparison operators (<, ==) returning 1 or 0, as a new lowest-precedence level in the grammar.
  • Integer mode with long long and ckd_add/ckd_mul to detect overflow (Type Limits).
  • Hexadecimal and binary output, for example a hex command that prints ans with %llx.
  • Build an expression tree instead of evaluating immediately, so an expression can be stored and re-evaluated when its variables change. Each tree node is a struct with an operator and child pointers, like the binary search trees lesson.
  • Reading from a file of calculations given on the command line (Command-Line Arguments).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. With this calculator's grammar, what is the value of 10 - 3 - 2?

    The loop in parse_expression makes subtraction left-associative, so it computes (10 - 3) - 2 = 5.
  2. 2. Why does 2 + 3 * 4 evaluate the multiplication first?

    Each precedence level is a function, and deeper functions bind tighter. parse_term consumes 3 * 4 completely and returns 12 to parse_expression.
  3. 3. What does -2 ^ 2 give in this calculator, and why?

    parse_unary reads the minus, then calls parse_unary again, which reaches parse_power and computes 2 ^ 2 first. This matches the mathematical convention.
  4. 4. Why does the tokenizer cast characters to unsigned char before calling isdigit?

    On systems where char is signed, bytes above 127 are negative, which the ctype functions don't accept.
  5. 5. How does the parser stop quickly after the first error?

    No grammar loop continues on TOK_ERROR, so the recursion unwinds naturally and the first error message is kept.

Summary

  • A calculator splits into a tokenizer (characters to tokens) and a parser (tokens to values).
  • A recursive descent parser has one function per grammar rule; precedence comes from how deep a rule sits, associativity from loops (left) or recursion (right).
  • strtod with its end pointer makes number scanning easy; each token remembers its column for precise error carets.
  • Errors are recorded once with vsnprintf and stop the parser by turning the current token into TOK_ERROR, so bad input never crashes the program.
  • A table of names and function pointers adds math functions without new parsing code; a small struct array holds variables and ans.
  • fgets plus a check for the newline detects overlong lines; isfinite rejects NaN and infinite results.

Next: Project: Student Records