/*********************** * * Syntax for passing functions around * ***************/ #include // A simple function. int doubleIt(int a) { return(2*a); } // And another with the same arguments and return value. int halfIt(int a) { return (a/2); } int main() { int z = 17; int answer; int (*mysteryFunc)(int); // here we declare mysteryFunc // as a pointer to a function which // takes an integer argument and returns // and integer. printf( " Hello \n " ); printf( " twice %i is %i \n", z, doubleIt(z) ); printf( " half %i is %i \n", z, halfIt(z) ); mysteryFunc = &doubleIt; // and here we assign whichFunc to // the address of the doubleIt function. mysteryFunc = doubleIt; // This syntax also works. answer = mysteryFunc(z); // And here we invoke it. answer = (*mysteryFunc)(z); // Or this way. printf( " Mystery guest: %i is %i \n", z, answer ); // Here's how we compare two functions. if ( mysteryFunc == doubleIt ) { printf (" Yup, the mystery guest is 'doubleIt' \n"); } else { printf (" Nope - something funny here.' \n"); } // Or this. if ( mysteryFunc == &doubleIt ) { printf (" Yup, the mystery guest is 'doubleIt' \n"); } else { printf (" Nope - something funny here.' \n"); } // Or even this. Go figure. if ( *mysteryFunc == doubleIt ) { printf (" Yup, the mystery guest is 'doubleIt' \n"); } else { printf (" Nope - something funny here.' \n"); } }