I created 3 void functions that will return the result of the given pow (either int, float or double) to the origin.
#include <assert.h>
#include <float.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
enum base_type { BASE_TYPE_INT, BASE_TYPE_FLOAT, BASE_TYPE_DOUBLE };
void my_pow_int(int *b, int n) {
int a = *b;
*b = pow(a,n);
}
void my_pow_float(float *b, int n) {
float a = *b;
*b = powf(a,n);
}
void my_pow_double(double *b, int n) {
double a = *b;
*b = pow(a,n);
}
Next I created a function that takes 3 parameters and then decides what function from above should be executed.
void my_pow(void *b, int n, enum base_type type) {
if (type == BASE_TYPE_INT){
*b = my_pow_int(b, n);
}
if (type == BASE_TYPE_FLOAT){
*b = my_pow_float(b, n);
}
else{
*b = my_pow_double(b, n);
}
}
I now do have the problem that when I give he function a void pointer, It will not compile because of the casting. I don't get what I am doing wrong here.
CodePudding user response:
The functions that you're calling dereference b
with the proper pointer type, and those functions don't return anything, so no need to set anything in my_pow
:
void my_pow(void *b, int n, enum base_type type) {
if (type == BASE_TYPE_INT){
my_pow_int(b, n);
}
else if (type == BASE_TYPE_FLOAT){
my_pow_float(b, n);
}
else{
my_pow_double(b, n);
}
}
CodePudding user response:
First problem: You my_pow_* functions return void, so *b = my_pow...
doesn't work. It doesn't need to, since you're doing an in-place assignment in your functions.
If you fix that, you can just call your function as
double val = 3.0;
my_pow(&val, 2, BASE_TYPE_DOUBLE);