Skip to content

zerfithel/calc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 

Repository files navigation

Calculator in C

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.

How to use

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

How it works

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

How does AST work? (Abstract Syntax Tree)

It is explained here wikipedia.org/wiki/Abstract_syntax_tree

About

AST-Based Calculator written in C

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages