#ifndef STACK_H #define STACK_H #define printerr(format, ...) printf("error: " format "\n", ##__VA_ARGS__) #define EMPTY_STACK_ERR "stack empty" #define SHORT_STACK_ERR "not enough elements on stack" #ifndef MAX_STACK #define MAX_STACK 100 #endif // MAX_STACK int sp = 0; double val[MAX_STACK]; /* length: current length of stack */ #define length() sp /* push: push f onto value stack */ #define push(x) \ ((sp < MAX_STACK) ? val[sp++] = x : printerr(FULL_STACK_ERR, (double) (x))) /* pop: pop and return top value from stack */ double pop(void) { return sp ? val[--sp] : (printerr(EMPTY_STACK_ERR), 0); } /* peek: return top value from stack, leave stack unchanged */ #define peek() (sp ? val[sp-1] : (printerr(EMPTY_STACK_ERR), 0)) /* clear: clear stack */ #define clear() (sp = 0) /* dup: duplicate top element */ #define dup() do { double tmp = peek(); push(tmp); } while (0) /* swap: swap top two elements */ #define swap() \ do { if (sp < 2) printerr(SHORT_STACK_ERR); else { \ double tmp = peek(); \ val[sp-1] = val[sp-2], val[sp-2] = tmp; \ } \ } while (0) #undef printerr #endif // STACK_H