Skip to content

Instantly share code, notes, and snippets.

@proudlygeek
Created April 9, 2012 14:28
Show Gist options
  • Select an option

  • Save proudlygeek/2343825 to your computer and use it in GitHub Desktop.

Select an option

Save proudlygeek/2343825 to your computer and use it in GitHub Desktop.
C Callbacks
#include <stdio.h>
// The original function (adds two number and sets
// the results into the first one
void add(int *x, int *y)
{
*x = *x + *y;
}
void sub(int *x, int *y)
{
*x = *x - *y;
}
// Runs the callback given some parameters. Can also be thinked
// as a "decorator".
//
// TODO: Find a way to pass cb's arguments without polluting
// the main function.
void call_callback(int *a, int *b, void (*cb)(int *, int *))
{
(*cb)(a, b);
}
int main(int argc, const char *argv[])
{
int a = 2;
int b = 3;
printf("%d + %d = ", a, b);
call_callback(&a, &b, add);
printf("%d\n", a);
printf("%d - %d = ", a, b);
call_callback(&a, &b, sub);
printf("%d\n", a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment