Skip to main content

Command Palette

Search for a command to run...

Function pointer

Published
•1 min read•View as Markdown
#include <stdio.h> // The following function subtracts two numbers
int subtract(int a, int b) { 
    return a - b;
}
int add(int a, int b) { 
    return a + b;
} 
int main() { 
// The command declares function pointers
int (*functionPtr)(int, int);
functionPtr = subtract;
printf("The subtraction of two numbers: %d\n\n", functionPtr(7, 4));

functionPtr = add;
printf("The addition of two numbers: %d\n", functionPtr(7, 4));

return 0;
}

Output:

i) Declaring a function pointer:

Syntax:

return_type (*pointer_name)(parameter_list);

Example:

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

ii) Assigning a function address to a function pointer:

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

22 views

More from this blog

P

Programming Tutorials

89 posts