2023-07-10 17:48:07 +02:00
|
|
|
#ifndef STACK_H
|
|
|
|
|
|
|
|
#define STACK_H
|
2023-07-10 17:58:08 +02:00
|
|
|
#define printerr(format, ...) printf("error: " format "\n", ##__VA_ARGS__)
|
2023-07-10 17:48:07 +02:00
|
|
|
|
2023-07-16 13:31:57 +02:00
|
|
|
/* ERROR MESSAGES */
|
2023-07-10 17:48:07 +02:00
|
|
|
#define EMPTY_STACK_ERR "stack empty"
|
|
|
|
#define SHORT_STACK_ERR "not enough elements on stack"
|
2023-07-16 13:31:57 +02:00
|
|
|
#define FULL_STACK_ERR "stack full, can't push %g"
|
2023-07-10 17:48:07 +02:00
|
|
|
|
|
|
|
#ifndef MAX_STACK
|
|
|
|
#define MAX_STACK 100
|
|
|
|
#endif // MAX_STACK
|
|
|
|
|
2023-07-10 20:33:26 +02:00
|
|
|
int sp = 0;
|
|
|
|
double val[MAX_STACK];
|
2023-07-10 17:48:07 +02:00
|
|
|
|
|
|
|
/* 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
|