Function Pointer in C

By | February 18, 2023

In C programming language, a function pointer is a variable that holds the address of a function. It allows us to pass functions as arguments to other functions, store functions in arrays or structures, and call functions indirectly.

Declaring Function Pointer in C:
To declare a function pointer, you need to specify the return type and the parameter types of the function that the pointer will point to. Here’s an example:

int (*p)(int, int);

This declares a function pointer p that points to a function that takes two int arguments and returns an int.

To assign a function to a pointer, you simply use the name of the function:

int sum(int x, int y) {
    return x + y;
}

p = sum;

Now p points to the sum function.

To call the function using the pointer, you use the * operator:

int result = (*p)(3, 4);

This will call the function that p points to with arguments 3 and 4, and store the result in the result variable.

Alternatively, you can use the function pointer as if it were a regular function:

int result = p(3, 4);

This does the same thing as the previous example, but it’s a bit more concise.

Function pointers are a powerful feature of C that allows you to write more flexible and reusable code.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.