Simple calculator that uses AST (Abstract Syntax Tree).
Supports:
add (+)
sub (-)
mul (*)
div (/)
mod (%)
pow (^)
root ([)
I plan to add factorial (!) and bitwise left and right shift (<< and >>) operators.
Compilation:
gcc src/*.c src/*.h -o calc -lm
To use you can do
./calc <arithmetic>
to calculate single arithmetic or
./calc <arithmetic_1> <arithmetic_2>
to calculate multiple arithmetics
or to enter interactive (shell-like) mode do:
./calc
to quit enter q and to clear screen enter c
It works by getting input from user character by character and allocating string on the heap with getstring() function and saving it inside global variable *expr. Then it calls parser that (level 1) that will build AST tree out of the given arithmetic expression.
Parser levels: level 1 - understands + and - level 2 - understands * / and % level 3 - understands ^ and [ level 4 - understands ( and )
Level 1, calls level 2, level 2 calls level 3 and level 3 calls level 4 then level 4 does it job, then it comes back to level 3, level 2 and then level 1. When AST tree is built then the eval() function evaluates it by reading AST tree, and if type of node is NODE_NUMBER, then just returns it and if its NODE_OPERATOR then recurse calls on left and right node and performs operation on it (if operator is + then does left + right) until the whole tree is done (it doesnt check for sequence of actions because the parser built the tree so it wont have to). Then it just prints the result to terminal. There are comments in code if you want to see how it works
It is explained here wikipedia.org/wiki/Abstract_syntax_tree