top

Search

C Tutorial

.

UpGrad

C Tutorial

Function Pointer in C

Understanding Function Pointers in C

A function pointer in C is a variable that stores the address of a function. It allows you to refer to a function by using its pointer and later call the function using that function pointer. This provides flexibility in calling functions dynamically and can be useful in scenarios where you want to select and call different functions based on certain conditions or requirements.

The function pointers in C are declared using the asterisk (*) operator to obtain the value saved in an address.

Advantages of Function Pointers

A function pointer in C is useful to generate function calls to which they point. Hence, the programmers can pass them as arguments. The function pointers enhance the code’s readability. You can access many identical functions using a single line of code.

Other prominent advantages of function pointer in C include passing functions as parameters to other functions. Therefore, you can create generic functions which can be used with any function provided that it possesses the right signature.

Syntax of Function Pointer in C

Here is the function pointer syntax in C.

return type (*ptr_name)(type1, type2...);

Let’s look at an example:

int (*ip) (int);

*ip is a pointer in the above declaration. It points to a function that returns an int value and also accepts an integer value as an argument.
Functions Using Pointer Variables

In C, you can pass pointers as function arguments and return pointers from the function. If you want to pass pointers in the function, you just need to declare the function parameter as a pointer type.

Here’s a C program demonstrating functions using pointer variables.

#include <stdio.h>

void increment(int *numb);

int main()
{
int numb = 10;
printf("The number before increment is: num = %d\n", numb);
increment(&numb);
printf("The output after increment is: num = %d\n", numb);
return 0;
}

void increment(int *numb) {
(*numb)++;
}

Output:

The number before increment is: num = 10
The output after increment is: num = 11

In the above program, the increment function increments an integer’s value using a pointer. The numb variable is declared and initialized to 10. Subsequently, we call the increment function and pass the address of numb variable. Lastly, the value of numb is printed at the output.

Referencing and Dereferencing of Function Pointer in C

Referencing a function pointer in C refers to assigning the address of a function to the pointer using the ‘&’ operator. On the other hand, Dereferencing a function pointer in C refers to accessing a function and invoking it with arguments using the ‘*’ operator.

Program to pass pointers with functions in C

If you want to pass pointers to functions in C, you must define the function that accepts a pointer parameter. Subsequently, you need to pass the address of the array or variable that you want to work with.

Here's a program that demonstrates passing pointers with functions:

#include <stdio.h>

// C program to swap two integers through pointers
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}

int main()
{
int a = 50;
int b = 100;

printf("The numbers before swap: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("The numbers after swap: a = %d, b = %d\n", a, b);

return 0;
}

Output:

he numbers before swap: a = 50, b = 100
The numbers after swap: a = 100, b = 50

The above program shows that the swap function accepts two integer pointers as parameters. Within the function, we’ve used these pointers to access and swap the variables’ values they point to.

Example for Function Pointer in C

Here’s an example program that demonstrates function pointer in C.

#include <stdio.h>

// The following function subtracts two numbers
int subtract(int a, int b) {
return a - b;
}


int main()
{
// The command declares function pointers
int (*subPtr)(int, int);


subPtr = subtract;
printf("The subtraction of two numbers: %d\n", subPtr(7, 4));

return 0;
}

Output:

The subtraction of two numbers: 3

In the above program, we declare a function pointer subPtr that points to a function that accepts two integers as arguments and returns an integer. The syntax (*subPtr)(int, int) declares the function pointer.

Within the main function, we assign the subtract function’s address to the function pointer with the help of subPtr = subtract. So, subPtr now points to the subtract function. Subsequently, we call the function via the function pointer by command subPtr(7, 4).
Function Pointer Operations

The below section discusses some common operations that you can accomplish using function pointers:
i) Declaring a function pointer:

Syntax:

return_type (*pointer_name)(parameter_list);

Example:

int (*funcPtr)(int, int); // This function pointer to a function accepts two int parameters and returns int

ii) Assigning a function address to a function pointer:

sumPtr = add; // Assigns the address of a function to a function pointer.

Declaring a Function Pointer in C

Since each function has a unique memory address, you can use the function pointers in C to point to the foremost executable code within a function body.

Declaration of function pointer in C
As seen from the example in the above figure, the function add() adds two integer numbers. The function name points to the address of the function itself. Hence, we’ve used a function pointer fptr that holds the address of the start of the function add(a, b) (the address is 1001 in the above example).
Note: Before using a function pointer, you must declare it to inform the compiler about the type of function the particular pointer can point to.

Calling Functions Using Pointers

Calling a function using a pointer is the same as calling a function using the function’s name.

The following program demonstrates calling functions using pointers.

#include <stdio.h>

void add(int a, int b)
{
int sum = a + b;
printf("The addition of %d and %d is: %d\n", a, b, sum);
}

int main()
{

void (*addPtr)(int, int); // Function pointer declaration
addPtr = add; // Assigning address of add function
addPtr(7, 8); // Calling the function using function pointer
return 0;
}

Output:

The addition of 7 and 8 is: 15

In the above program, the add function accepts two integers as arguments, computes their sum, and displays the output. The declaration of addPtr function pointers happens with the parameter types and return type that match the functions they would point to.

addPtr = add command assigns the add function’s address to the addPtr function pointer. AddPtr(7, 8) calls the add function through the addPtr function pointer (with the input arguments).

Function Pointer Arrays

An array of function pointer in C stores and handles multiple function pointers. They are useful when you need to choose and dynamically call a set of related functions depending on specific conditions.

Function Pointer to Function Pointer

With the help of a function pointer, you can refer to another function pointer. It is helpful in scenarios where you wish to dynamically choose and invoke any function pointer.

Function Pointer and Callback Functions

Definition of Callback Functions

Functions in C can define a function pointer as function pointer as argument in C and subsequently call it within the function body. These passed functions are known as callback functions.

Function Pointer and Arrays

Array of Function Pointers

Similar to other data types, you can make an array in C to store function pointers. You can access function pointers from their indexes just like you access normal array values. Consequently, you would create an array of function pointers wherein each array element holds a function pointer pointing to various functions.

Array of Function Pointers to Functions

When using an array of function pointers, the array accepts the addresses of different functions. Subsequently, the program will call the appropriate function depending on the index number.

Common Mistakes and Pitfalls

Being familiar with the common mistakes and pitfalls helps you to write more reliable and accurate code using function pointer in C. Let’s look at their details.

i. Wrong Function Signature:

You must make sure that the function pointer declaration matches the signature of the function that is assigned to it. If they don’t match, you will observe runtime issues or compilation errors.

ii. Lifetime of Function Pointers:

You must consider the function pointers’ lifetime. Don’t use function pointers to reference local variables that reach out of scope. The reason is it can show undefined behaviour when trying to access those pointers in the future.

iii. Null Pointer Dereference:

Before you call a function using a function pointer, make sure the function pointer is not null. Dereferencing a null function pointer will show undefined behaviour that might produce crashes or unforeseen program behaviour.

Applications of Function Pointers

Let’s check out some prominent applications of function pointers.

i. Callback Functions:

Commonly, function pointers are often used for employing callback mechanisms. So, you can pass a function pointer in the form of an argument to another function. This allows the called function to invoke the particular function in the future. Usually, this aspect is used while implementing frameworks or libraries or in event-driven programming

ii. Function Wrappers:

You can use function pointers to create wrappers around the existing functions. This approach is helpful when you want to implement additional behaviour or change the utility of an existing function without directly changing its source code.

iii. Sorting and Searching:

You can employ generic sorting and searching algorithms using function pointers. Specifically, you can pass a function pointer that defines the comparison or ordering logic. This allows you to reuse the searching or sorting algorithm with various types of data. Hence, your code becomes more flexible and reusable.

iv. Event Handling:

You can use function pointers to manage events in an event-driven system. Rather than using a distinct function for every event, you can store the function pointers related to varied events. Subsequently, you can call the suitable function when an event happens. So, it disassociates event sources from event handlers and enables flexible event handling.

Conclusion

Function pointers in C help you to manipulate and store functions as data. They are useful in various applications to improve the extensibility and flexibility of your code.

Tutorials certainly assist you in reinforcing your C fundamentals, including function pointer in C. Along with that, you can pursue upGrad’s Executive Post Graduate Programme in Software Development by IIIT-B to ensure career advancement. Pursuing this course will familiarise you with various facets of software development ranging from computer science basics to creating an intuitive web UI. After completing the course, you can embark on your career in the field of STEM!

Enroll now to start your journey!

FAQs

1. How to safely return a pointer from a function?

You can safely return a pointer from a function using two ways. (i) Create return variables using the keyword static or dynamically create them at run time. (ii) You can use arguments that are passed by their reference since such functions are available in the calling function scope.

2. What are the common use cases for function pointers in C?

The function pointers are widely used in scenarios like implementing function dispatching, function tables, callback mechanisms, and function-based polymorphism.

3. What is the typedef function pointer in C

The typedef function pointer in C helps you to generate a custom type that denotes a specific function signature. It lets you define a more readable and shorter alias for your function pointer type. Specifically, it can be helpful if you are working with multiple function pointers with identical signatures.

4. What is the size of a function pointer in C?

The size of a function pointer is not fixed and entirely depends on its underlying architecture, as well as the compiler being used. Typically function pointers in 32-bit systems are usually 4 bytes, while the ones on 64-bit systems are 8 bytes in size.

Leave a Reply

Your email address will not be published. Required fields are marked *