Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Last active April 24, 2021 11:25
Show Gist options
  • Save ibeauregard/efe8ef8a86e57002fbe551b1398eb4e0 to your computer and use it in GitHub Desktop.
Save ibeauregard/efe8ef8a86e57002fbe551b1398eb4e0 to your computer and use it in GitHub Desktop.
Introducing function pointers
/* int_stack.h */
typedef struct int_stack IntStack;
struct int_stack {
void (*push)(IntStack* this, int value);
int (*pop)(IntStack* this);
int (*peek)(IntStack* this);
bool (*isEmpty)(IntStack* this);
void (*delete)(IntStack** this);
};
IntStack* new_stack();
/* main.c */
#include "int_stack.h"
#include <stdio.h>
int main()
{
IntStack* stack = new_stack();
for (int i = 5; i > 0; i--) {
stack->push(stack, i);
}
printf("At the top of the stack is `%d`\n\n", stack->peek(stack));
while (!stack->isEmpty(stack)) {
printf("`%d` was popped from the stack\n", stack->pop(stack));
}
stack->delete(&stack);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment