Skip to main content

Posts

Showing posts with the label Pointer to Functions

Pointer to Functions

One of the powerful features of C is to define pointers to functions. Function pointers are pointers ie; variables, which point to the address of a function. Like other pointer variables, function pointers can be declared, assigned values and then used to access the function they point to. Function pointers are declared as follows return_type (* function_pointer_name) (argument_type1,argument_type2…); Example: int (*fp)(float,char) The function pointer fp points to a function that takes one float and one char arguments and returns an int value. Like other pointer variables, function pointers must be initialized prior to use. It is easy to assign the address of a function to a function pointer by using the name of the function. The following example illustrates the use of function pointer to call two different functions. int add(int a, int b) { return a+b; } int sub(int a, int b) { return a-b; } int main() { int (*fptr)(int,int); fptr=add; printf(“%d\n”,fptr(2,3)