Skip to content

Instantly share code, notes, and snippets.

@alexbowe alexbowe/funky_typedef.c
Last active Dec 20, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Aug 5, 2013

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

@alexbowe

This comment has been minimized.

Copy link
Owner Author

commented Aug 13, 2013

@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
You can’t perform that action at this time.