Pointer with function in C
We can use pointers with functions in following ways:
Function returning pointer
In C language, a function can even return a pointer like other data types.
The syntax for function returning a pointer is:
|Program to demonstrate a function returning pointer
int *sum(int a,int b)
|In the above program, the function sum() is returning pointer as int *sum(int a,int b).
This function has been called within main() by taking a pointer variable s as int *s and assigning function calling statement to variable s as s=sum(10,14);
Pointer to function
Function also has an address in memory. This address is used when the function is called.
By storing this address in a function pointer, the function can also be called through this pointer.
Using function pointers, functions are passed as arguments to other functions.
|Program to demonstrate the use of pointer to function.
void fun(int val)
|In the above program, the function fun(int val) is defined.
Function pointer has been declared as void (*fp)(int).
This pointer looks similar to function definition i.e. void is the return type and int is within parenthesis specifying argument of int type.
fp= &fun statement assigns the address of function fun in function ponter fp.
fp(10) calls function fun with argument value 2.