Created
March 21, 2025 07:09
-
-
Save kjsingh/c81aa5e6944423a4422602587972332a to your computer and use it in GitHub Desktop.
Func pointers and 'methods' in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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