Last active
December 20, 2015 15:19
-
-
Save alexbowe/6153307 to your computer and use it in GitHub Desktop.
C function pointer typedef example (for nicer variable declarations).
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
/* | |
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 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
This takes me back down memory lane to 1994 :-)