DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Function Pointers

  • submit to reddit
        // Using function pointers to decide which function to run at runtime

int plus(int a, int b) { return a+b; }
int minus(int a, int b) { return a-b; }
int calc(int a, int b, int (*funcptr)(int, int)){ return funcptr(a,b); }
int main(int argc, char **argv) {
	int x = 11;
	int y = 7;
	int z = calc(x, y, &plus);
	printf("z: %i\n",z); // z: 18
	z = calc(x, y, &minus);
	printf("z: %i\n",z); // z: 4
	return 1;