fork download
  1. #ifndef STACK_H
  2. #define STACK_H
  3. #include <assert.h>
  4. #include <stdlib.h>
  5. #define stack_of(T) struct { size_t top; T value[]; }
  6.  
  7. #define operate(list, ...) { \
  8.   size_t x = list ? list->top : 0 \
  9.   , y = x + 1; \
  10.   if ((x & y) == 0) { \
  11.   void *temp = realloc(list, sizeof *list \
  12.   + (x + y) * sizeof list->value[0]); \
  13.   if (!temp) \
  14.   return EXIT_FAILURE; \
  15.   list = temp; \
  16.   } \
  17.   __VA_ARGS__; \
  18. }
  19.  
  20. #define push(list, v) operate(list, list->value[x] = v; list->top = y)
  21. #define pop(list) (assert(list && list->top), list->value[--list->top]); \
  22.   operate(list, )
  23. #endif
  24.  
  25. // #include "stack.h" // embedded above
  26. #include <stdio.h>
  27. int main(void) {
  28. stack_of(int) *fubar = NULL;
  29. int x;
  30. push(fubar, 42);
  31. push(fubar, -1);
  32. x = pop(fubar); printf("popped: %d\n", x);
  33. x = pop(fubar); printf("popped: %d\n", x);
  34. x = pop(fubar); printf("popped: %d\n", x);
  35. free(fubar);
  36. }
Runtime error #stdin #stdout #stderr 0s 4380KB
stdin
Standard input is empty
stdout
popped: -1
popped: 42
stderr
prog: prog.c:34: main: Assertion `fubar && fubar->top' failed.