Skip to content

Instantly share code, notes, and snippets.

@alexbowe
Last active December 20, 2015 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexbowe/6153307 to your computer and use it in GitHub Desktop.
Save alexbowe/6153307 to your computer and use it in GitHub Desktop.
C function pointer typedef example (for nicer variable declarations).
/*
I have read a bunch of posts about function pointers,
such as http://denniskubes.com/2013/03/22/basics-of-function-pointers-in-c/
but I rarely see this *one weird trick*.
It is C's (admittedly clunky) syntax for typedefing a function pointer of a given signiature.
Hide the clunkiness in the typedef to keep your code tidy and maintainable.
*/
#include <stdio.h>
/* Syntax: typedef return_type (*name_of_typedef) (parameter_types) */
typedef void (*foo_fun) (int);
/* Here is a function with the same calling signature as a foo_fun we typedefed: */
void foo(int i) {
printf("hello %dth cruel world\n", i);
}
int main() {
/* The following line would otherwise be: void (*foo_fun)(int) my_foo = foo; */
foo_fun my_foo = foo;
my_foo(7);
}
@tseemann
Copy link

tseemann commented Aug 5, 2013

This takes me back down memory lane to 1994 :-)

@alexbowe
Copy link
Author

@tseemann Haha :D I didn't know much C back then (actually, none). My brothers showed me this in my first year of uni ^^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment