Page 185 - C-Language
P. 185

returnType (*name)(parameters)


        A mnemonic for writing a function pointer definition is the following procedure:

            1.  Begin by writing a normal function declaration: returnType name(parameters)
            2.  Wrap the function name with pointer syntax: returnType (*name)(parameters)


        Basics


        Just like you can have a pointer to an int, char, float, array/string, struct, etc. - you can have a
        pointer to a function.


        Declaring the pointer takes the return value of the function, the name of the function, and the
        type of arguments/parameters it receives.

        Say you have the following function declared and initialized:


         int addInt(int n, int m){
             return n+m;
         }


        You can declare and initialize a pointer to this function:


         int (*functionPtrAdd)(int, int) = addInt; // or &addInt - the & is optional


        If you have a void function it could look like this:


         void Print(void){
             printf("look ma' - no hands, only pointers!\n");
         }


        Then declaring the pointer to it would be:


         void (*functionPtrPrint)(void) = Print;


        Accessing the function itself would require dereferencing the pointer:


         sum = (*functionPtrAdd)(2, 3); //will assign 5 to sum
         (*functionPtrPrint)(); //will print the text in Print function


        As seen in more advanced examples in this document, declaring a pointer to a function could get
        messy if the function is passed more than a few parameters. If you have a few pointers to
        functions that have identical "structure" (same type of return value, and same type of parameters)
        it's best to use the typedef command to save you some typing, and to make the code more clear:


         typedef int (*ptrInt)(int, int);

         int Add(int i, int j){
             return i+j;




        https://riptutorial.com/                                                                             161
   180   181   182   183   184   185   186   187   188   189   190