Skip to content

Instantly share code, notes, and snippets.

@webgtx
Last active April 17, 2022 01:23
Show Gist options
  • Save webgtx/f451a6669060c14c0230d800239a76be to your computer and use it in GitHub Desktop.
Save webgtx/f451a6669060c14c0230d800239a76be to your computer and use it in GitHub Desktop.
Callbacks in C
// Only INT, don't trying use arrays with char
void foreach(int *arr, int len, void (*callback) (int item, int idx)) {
unsigned idx = 0;
for (idx; idx < len; idx++)
callback(arr[idx], idx);
}
int main() {
int arr[] = {1, 3, 5, 6};
int arr_len = sizeof arr / sizeof arr[0];
void cb (int n, int idx) {
printf("cb: %-3i:%2i\n", n, idx);
}
foreach(arr, arr_len, cb);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment