Programming in C

(Barry) #1
Pointers to Functions 273

while ( *cptr )
++cptr;
return cptr - string;
}


int main (void)
{
int stringLength (const char *string);


printf ("%i ", stringLength ("stringLength test"));
printf ("%i ", stringLength (""));
printf ("%i\n", stringLength ("complete"));

return 0;
}


Program 11.15 Output


17 0 8


Pointers to Functions


Of a slightly more advanced nature, but presented here for the sake of completeness, is
the notion of a pointer to a function.When working with pointers to functions, the C
compiler needs to know not only that the pointer variable points to a function, but also
the type of value returned by that function as well as the number and types of its argu-
ments.To declare a variable fnPtrto be of type “pointer to function that returns an int
and that takes no arguments,” the declaration


int (*fnPtr) (void);


can be written.The parentheses around fnPtrare required because otherwise the C
compiler treats the preceding statement as the declaration of a function called fnPtrthat
returns a pointer to an int(because the function call operator ()has higher precedence
than the pointer indirection operator
).
To set your function pointer pointing to a specific function, you simply assign the
name of the function to it. So, if lookupis a function that returns an intand that takes
no arguments, the statement


fnPtr = lookup;


stores a pointer to this function inside the function pointer variable fnPtr.Writing a
function name without a subsequent set of parentheses is treated in an analogous way to
writing an array name without a subscript.The C compiler automatically produces a


Program 11.15 Continued

Free download pdf