exc/k&r/04-funcs-and-prog-struct/04-calc/04-glob-stack.h

50 lines
1.2 KiB
C
Raw Normal View History

#ifndef STACK_H
#define STACK_H
2023-07-10 17:58:08 +02:00
#define printerr(format, ...) printf("error: " format "\n", ##__VA_ARGS__)
/* ERROR MESSAGES */
#define EMPTY_STACK_ERR "stack empty"
#define SHORT_STACK_ERR "not enough elements on stack"
#define FULL_STACK_ERR "stack full, can't push %g"
#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];
/* 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