Skip to content

Instantly share code, notes, and snippets.

@oguz-ismail
Created October 17, 2022 06:47
Show Gist options
  • Save oguz-ismail/abd4dfa26a164cd0d0a41f7d2420dc64 to your computer and use it in GitHub Desktop.
Save oguz-ismail/abd4dfa26a164cd0d0a41f7d2420dc64 to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef STACK_SIZE_MAX
#define STACK_SIZE_MAX 1000
#endif
double stack[STACK_SIZE_MAX];
size_t stack_size;
static double
pop(void) {
if (stack_size == 0) {
fputs("stack empty\n", stderr);
exit(1);
}
stack_size--;
return stack[stack_size];
}
static void
push(double element) {
if (stack_size == STACK_SIZE_MAX) {
fputs("stack full\n", stderr);
exit(1);
}
stack[stack_size] = element;
stack_size++;
}
int
main(int argc, char *argv[]) {
size_t i;
char *token, *end;
double lhs, rhs, value;
for (i = 1; i < argc; i++) {
token = argv[i];
if (strlen(token) == 1 && strspn(token, "+-x/") == 1) {
rhs = pop();
lhs = pop();
switch (*token) {
case '+':
value = lhs + rhs;
break;
case '-':
value = lhs - rhs;
break;
case 'x':
value = lhs * rhs;
break;
case '/':
value = lhs / rhs;
break;
}
}
else {
errno = 0;
value = strtod(token, &end);
if (errno != 0 || end == token || *end != '\0') {
fprintf(stderr, "invalid token: %s\n", token);
return 1;
}
}
push(value);
}
while (stack_size > 0)
printf("%g\n", pop());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment