0% found this document useful (0 votes)
4 views

Function Pointer Ex Code

C questions and answers

Uploaded by

dedmond030
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Function Pointer Ex Code

C questions and answers

Uploaded by

dedmond030
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <stdio.

h>

// Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);

int add(int a, int b) {


return a + b;
}

int subtract(int a, int b) {


return a - b;
}

int multiply(int a, int b) {


return a * b;
}

int divide(int a, int b) {


if (b != 0)
return a / b;
else {
printf("Error: Division by zero\n");
return 0;
}
}

Step 2: Use Function Pointers

Next, define a function that takes a function pointer as an argument along with two integers.
This function will call the pointed-to function with the provided integers.

c
Copy code
// Function pointer type definition
typedef int (*operation_t)(int, int);

void perform_operation(operation_t operation, int x, int y) {


int result = operation(x, y);
printf("Result: %d\n", result);
}

Step 3: Main Function

Finally, use the function pointers in the main function to call the different arithmetic
operations.

c
Copy code
int main() {
int a = 10, b = 5;

// Perform addition
perform_operation(add, a, b);

// Perform subtraction
perform_operation(subtract, a, b);

// Perform multiplication
perform_operation(multiply, a, b);

// Perform division
perform_operation(divide, a, b);

return 0;
}

Full Example Code

Here is the complete code:

c
Copy code
#include <stdio.h>

// Function prototypes
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);

// Function definitions
int add(int a, int b) {
return a + b;
}

int subtract(int a, int b) {


return a - b;
}

int multiply(int a, int b) {


return a * b;
}

int divide(int a, int b) {


if (b != 0)
return a / b;
else {
printf("Error: Division by zero\n");
return 0;
}
}

// Function pointer type definition


typedef int (*operation_t)(int, int);

void perform_operation(operation_t operation, int x, int y) {


int result = operation(x, y);
printf("Result: %d\n", result);
}

int main() {
int a = 10, b = 5;

// Perform addition
perform_operation(add, a, b);
// Perform subtraction
perform_operation(subtract, a, b);

// Perform multiplication
perform_operation(multiply, a, b);

// Perform division
perform_operation(divide, a, b);

return 0;
}

You might also like