Function Pointer is a variable that stores the address of a function. Function pointers provide a way to call functions indirectly, making them a powerful and flexible feature.
Incrementing a pointer (ptr++) moves it to the next memory location, while decrementing (ptr--) moves it to the previous location.
Initialize the function pointer by assigning it the address of a function with a matching signature.
calling a function through a function pointer involves using the function pointer as if it were a regular function. You can either use the dereference operator (*) or directly call the function pointer.
In this example:
1. The add function adds two integers.
2. The funcPtr function pointer is declared and initialized to point to the add function.
3. The function pointer is used to call the add function, passing it two arguments (3 and 5).
4. The result is printed.
Both (*funcPtr)(3, 5) and funcPtr(3, 5) are valid ways to call a function through a function pointer. The compiler understands that the variable funcPtr is a function pointer and handles the call appropriately.Passing function pointers as arguments in C allows you to implement dynamic behavior by choosing which function to execute at runtime.
This example defines two functions , 'add' and 'subtract' , for addition and subtraction. It introduces a generic 'operate' functions that takes a functions pointer along with two integers. In the 'main' functions , two functions pointers are declared and initialized to point to 'add' and 'subtract'. By invoking 'operate' with these functions pointers, the code dynamically selects and executes the desired operation, showcasing flexibility and reusability .
Was this helpful?