Simple (yet quite interesting to build) console calculator written in C.
Disclaimer
I dont know neither how to properly build this type of parsing nor how to properly code in plain C, so this is just for fun and exercise.
-
Calculate any math expression of basic operators (
+
,-
,*
,/
) and brackets()
-
Parser error handling with handy messages
-
Console arguments support:
Just use your terminal of choice and execute program:
> .\calc.exe
or pass flag -i
for interactive mode:
> .\calc.exe -i
Use flag -h
to view all possible arguments:
> .\calc.exe -h
Project uses xmake for building, so install it first.
To build, run
> xmake build calc
To test builded executable run
> xmake run calc
Program makes roughly these steps to transform initial string expression and evaluate it:
-
Tokenization: each independent part of the expression (token) is defined and a flat list of these tokens is created.
For example, if input string was
(1 + 1) / 2
, list of tokens will be(, 1, +, 1, ), /, 2
(Not just list of substrings but anyway) -
Block parsing: a flat list of tokens is transformed into a tree of (sort of) "blocks", so everything in parentheses will be recursively transformed into a separate list, and at the outer level there will be just a "block" token with a pointer to the list of underlying tokens.
Running program with
-v
flag will represent this step: -
Expression parsing: using a block tree, the program builds a binary tree of operations for each block.
- Simple tree building (For block
1 + 1
there will be tree with root node+
,1
nodes on left and right branches), - Tree sorting to make sure that multiplication and division come first,
- Recursive calls to include inner blocks.
- Simple tree building (For block
-
Tree evaluation: simplest part, just recursively call left and right branches, if it is a number node, return a number; then add, subtract, multiply or divide based on node operation.