Created
September 4, 2016 23:19
-
-
Save trichner/a19f28c98fc71b49d9f24b16521bb4ac to your computer and use it in GitHub Desktop.
RPN (Reverse Polnish Notation) Calculator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Simple reverse polnish notation calculator. | |
* | |
* Copyright (c) 2016 Thomas Richner | |
* MIT License, https://opensource.org/licenses/MIT | |
*/ | |
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
void panic(char* msg){ | |
fprintf(stderr, "%s\n", msg); | |
exit(-1); | |
} | |
int64_t eval(char** str){ | |
printf("%s\n", *str); | |
// ready next character | |
char op = **str; | |
(*str)++; | |
// end of string | |
if(op == 0){ | |
panic("error: invalid input."); | |
} | |
// a number literal | |
if(op >= '0' && op <= '9'){ | |
return op - '0'; | |
} | |
// recursively evaluate both arguments | |
int64_t exp1 = eval(str); | |
int64_t exp2 = eval(str); | |
// operate on the arguments | |
int64_t ret; | |
switch(op){ | |
case '+': | |
ret = exp1 + exp2; | |
break; | |
case '-': | |
ret = exp1 - exp2; | |
break; | |
case '*': | |
ret = exp1 * exp2; | |
break; | |
case '/': | |
ret = exp1 / exp2; | |
break; | |
default: | |
panic("error: invalid operation."); | |
break; | |
} | |
// * + X - X / | |
return ret; | |
} | |
// Usage: ./a.out '+5++89*92' | |
int main(int argc, char** argv){ | |
if(argc < 2){ | |
panic("Not enough arguments."); | |
} | |
char** strptr = &(argv[1]); | |
int64_t result = eval(strptr); | |
if(**strptr != '\0'){ | |
panic("error: invalid input."); | |
} | |
printf("Result: %li\n", result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment