Everything2
Near Matches
Ignore Exact
Full Text
Everything2

example of use of a function pointer

created by ariels

(idea) by cadmos (5.2 y) (print)   ?   (I like it!) Wed Mar 20 2002 at 6:54:16

#include <stdio.h>
#include <stdlib.h>
void zero(){ printf("zero\n"); };
void one(){ printf("one\n"); };
int main(int argc, char * argv[]){
     int i;
     void (*jumptable[2])();
     jumptable[0] = zero;
     jumptable[1] = one;
     i = atoi(argv[1]);
     jumptable[i]();
     return;
     };

What does it do? First, it creates an array of two function pointers. Then, it assigns values to that array from two functions. Then, it calls whichever one you specify on the command line. But... why? There are a few reasons. First off, you might have dynamically loaded the functions, so they couldn't be called directly. Second, speed. You could have just used a switch, but suppose you had lots of possibilites, and time mattered. A switch statement takes O(n) time, because it tests each possibility sequentially. If you put all your code in functions, and put pointers to those functions in an array, the program can lookup the function by index in the array and call it, all in O(1) time.

But... when would I *really* use a function pointer? callbacks.

printable version
chaos

callback function pointer Humans have six senses, why does everyone think we only have five? O(1) scheduler
alloca() Array of function pointers variable length string The C++ Programming Language Freakshow
How a Pope is chosen malloc Harvard Callbacks Using carrot seeds as birth control
MathML implicit Raze void *
pointer
Y'know, if you log in, you can write something here, or contact authors directly on the site. Create a New User if you don't already have an account.
  Epicenter
Login
Password

password reminder
register

Everything2 Help

Cool Staff Picks
Just another sprinkling of indeterminacy
Only a simple computer program
Other things nobody tells you about the south pole
Editor Log: August 2007
Dirt in my hair and toenails
William Gibson
Synesthesia
Euclid's algorithm
shotgun house
The end will be a sellout
Beowulf on Everything
And if your teacher is also a pervert?
How to be an improv musician
The Atrocities of Vlad III of Wallachia
New Writeups
antigravpussy
One fly amongst many(person)
sam512
Moon Base Shackleton, 1978(fiction)
Pavlovna
toy boy(person)
XWiz
tear jerker(review)
Heitah
Anarchy is Order(idea)
jessicaj
July 26, 2008(dream)
Berek
ABBA(person)
devolution
k-hole(place)
Nadine_2
The Sound Of Madness(review)
SwimmingMonkey
Conversations with Fo Fo, the Loneliest dog in Purgatory(fiction)
locke baron
lynx(thing)
Simulacron3
Reality, Dimensions and the Natural Ontology(essay)
SubSane
Making Love to a 9-Foot Woman(person)
Ouzo
Thoughts(idea)
antigravpussy
I fall silent, listening. The breadcrumbs are talking about us(person)
Everything 2 is brought to you by the letter C and The Everything Development Company