The following uses a simple function pointer, but what if I want to store that function pointer? In that case, what would the variable declaration look like?
#include <iostream>
#include <vector>
using namespace std;
double operation(double (*functocall)(double), double wsum);
double get_unipolar(double);
double get_bipolar(double);
int main()
{
double k = operation(get_bipolar, 2); // how to store get_bipolar?
cout << k;
return 0;
}
double operation(double (*functocall)(double), double wsum)
{
double g = (*functocall)(wsum);
return g;
}
double get_unipolar(double wsum)
{
double threshold = 3;
if (wsum > threshold)
return threshold;
else
return threshold;
}
double get_bipolar(double wsum)
{
double threshold = 4;
if (wsum > threshold)
return threshold;
else
return threshold;
}
That depends on your compiler and target environment, but most likely it points to ROM—executable code is almost always placed in read-only memory when available.
A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.
No. You must not because free(ptr) is used only when pointer ptr is previously returned by any of malloc family functions. Passing free a pointer to any other object (like a variable or array element) causes undefined behaviour.
2. What will we not do with function pointers? Explanation: As it is used to execute a block of code, So we will not allocate or deallocate memory.
You code is almost done already, you just seem to call it improperly, it should be simply
double operation(double (*functocall)(double), double wsum)
{
double g;
g = functocall(wsum);
return g;
}
If you want to have a variable, it's declared in the same way
double (*functocall2)(double) = get_bipolar;
or when already declared
functocall2 = get_bipolar;
gives you a variable called functocall2
which is referencing get_bipolar, calling it by simply doing
functocall2(mydouble);
or passing it to operation by
operation(functocall2, wsum);
You already (almost) have it in your code:
double (*functocall)(double) = &get_bipolar;
This defines a function pointer named functocall
which points to get_bipolar
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With