Skip to content

Instantly share code, notes, and snippets.

@kjsingh
Created March 21, 2025 07:09
Show Gist options
  • Save kjsingh/c81aa5e6944423a4422602587972332a to your computer and use it in GitHub Desktop.
Save kjsingh/c81aa5e6944423a4422602587972332a to your computer and use it in GitHub Desktop.
Func pointers and 'methods' in C
#include <stdio.h>
typedef struct _Opts {
int value;
int(*func)(int);
int(*next_value)(struct _Opts*);
} Opts;
Opts new_opts(int value);
int main(void)
{
char c = 0;
printf("Is Null \\0: %d\n", c == '\0');
Opts opts = new_opts(5);
printf("Value: %d\n", opts.value);
printf("Next Value: %d\n", opts.next_value(&opts));
return 0;
}
int square(int a) {
return a*a;
}
int next_value(Opts *opts) {
return opts->func(opts->value);
}
Opts new_opts(int value)
{
Opts opts;
opts.value = value;
opts.func = square;
opts.next_value = next_value;
return opts;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment