Function Pointers
C Programming
Programming Concepts
Code Implementation
Advanced Coding

How do function pointers in C work?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Function pointers in C are a powerful feature that allow programming languages like C to use functions as data. This means that functions can be assigned to variables, passed as arguments to other functions, or returned from other functions. In this article, we'll delve deep into how function pointers work in C, including technical explanations and examples.

Understanding Function Pointers

Function pointers hold the address of a function that can be called indirectly through the pointer. Using function pointers can lead to more flexible and reusable code because you can change the called function dynamically during runtime.

Syntax of Function Pointers

The syntax for declaring a function pointer is as follows:

c
return_type (*pointer_name)(parameter_list);

For example, a pointer to a function that takes two integers and returns an integer can be declared like this:

c
int (*func_ptr)(int, int);

Assigning Function to a Pointer

You can assign a function to a pointer without using the address-of operator &, although it's not wrong to use it. Here's how to assign a function to the previously declared pointer:

c
1int add(int a, int b) {
2    return a + b;
3}
4
5func_ptr = add;

or

c
func_ptr = &add;

Both are equivalent as function names convert to pointers automatically.

Calling a Function Through a Pointer

To call a function through a pointer, you use the usual function call syntax but with the function pointer’s name:

c
int result = func_ptr(3, 4);
printf("Result: %d\n", result);  // Output: Result: 7

Practical Use Cases of Function Pointers

Function pointers are particularly useful in several scenarios:

  • Modularizing code: Different functions can be passed to generic handling functions based on runtime decisions.
  • Callback functions: They are used extensively in event-driven programming to handle asynchronous events.
  • Table of functions: Often used in implementing jump tables like in the case of a state machine.

Example: Using Function Pointers as Callbacks

Function pointers allow you to customize the behavior of a library or a component without changing its source code by passing in callbacks.

c
1void forEach(int *array, int size, void (*func)(int)) {
2    for (int i = 0; i < size; i++) {
3        func(array[i]);
4    }
5}
6
7void printNumber(int n) {
8    printf("%d ", n);
9}
10
11int main() {
12    int numbers[] = {1, 2, 3, 4, 5};
13    forEach(numbers, 5, printNumber);
14    return 0;
15}

Safety and Precautions

Using function pointers requires careful handling:

  • Always ensure function pointers are initialized properly before using.
  • Function pointer types must match the function being pointed to, especially the types and number of parameters and the return type.

Troubleshooting Common Issues

  • Segmentation Faults: These often occur when function pointers are used before they are initialized.
  • Type Mismatch: Ensure there's strict adherence to the function signature including return type and parameters.

Summary Table

Feature of UseExplanation
FlexibilityFunction pointers allow runtime decision on which function to invoke.
ModularityCustomize or extend library functionalities through callbacks without altering original source.
Dynamic LinkingFunctions can be loaded dynamically at runtime which is pivotal in plugins and extension modules.

Conclusion

Function pointers are integral to achieving polymorphism and flexibility in C, making it possible to write general-purpose functions and scalable systems. Their careful use can significantly enhance the functionality and maintainability of the code, provided they are handled with the requisite caution due to their complexity and potential pitfalls.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.