Hi, I try to understand the concept of function pointers and I wrote an example for demonstration but it doesn't work as expected.
The return_error fuction never calls the mul_numbers.
Code:
#include <stdio.h>
#include <stdint.h>
typedef enum
{
status_ok = 1, // Operation terminated succesfully
status_hw_error, // Hardware error
status_busy, // Procedure in progress
status_invalid_param, // Invalid parameter
status_unknown_error // Unknown error
} status_t;
int add_numbers(int x, int y);
int mul_numbers(int x, int y);
typedef int (*operation_p)(int, int); // Declare a funciton pointer
status_t return_error(operation_p operation, int x, int y); // Function declaration (signature)
int main()
{
int a = 5;
int b = 3;
status_t error_code;
operation_p add; // Create a variable of type operation_p
operation_p mult; // Create a variable of type operation_p
add = add_numbers;
printf("Address of add: %d\n", &add);
error_code = return_error(add, a, b);
printf("Error: %d\n", error_code);
mult = mul_numbers;
printf("Address of mul %d\n", &mult);
error_code = return_error(mult, a, b);
printf("Error: %d\n", error_code);
return 0;
}
status_t return_error(operation_p operation, int x, int y)
{
printf("Address of operation: %d\n", &operation);
if (operation = &add_numbers)
{
printf("Addition callback error code\n");
if (operation(x, y) > 40)
{
return status_ok;
}
else if (operation(x, y) < 10)
{
return status_hw_error;
}
else
{
return status_unknown_error;
}
}
else if (operation = &mul_numbers)
{
printf("Multiply callback error code \n");
if (operation(x, y) < 30)
{
return status_ok;
}
else
{
return status_unknown_error;
}
}
}
int add_numbers(int x, int y)
{
return x + y;
}
int mul_numbers(int x, int y)
{
return x * y;
}
This is the printf output. The address of "operation" is always the same and differs from the addresses of "add" and "mul'
https://cboard.cprogramming.com/imag...BJRU5ErkJggg==