Reputation: 604
Let's assume, I have a function with a prototype like (in function.h
)
void function(int argument, bool flag);
This function has two variant behaviours, dependening on flag
.
Early on, in a module (module.h
, module.c
) I called that function:
#include "function.h"
function(argument1, true);
function(argument2, false);
Let's further assume, I want to pass this function into a module, inverting that dependencies:
void (* funcPtr)(int argument, bool flag);
void setFuncPtr(void (* func)(int argument, bool flag))
{
funcPtr = func;
}
Now I can have in function.c
:
#include "module.h"
setFuncPtr(function);
And in module.h
:
funcPtr(argument1, true);
funcPtr(argument2, false);
Is there a way to have two pointers, each pointing to the function, but with different, hardcodes values for flag
? Like:
void (* funcPtrTrue)(int argument, bool flag);
void (* funcPtrFals)(int argument, bool flag);
/* Or, even better
void (* funcPtrTrue)(int argument);
void (* funcPtrFals)(int argument);
*/
void setFuncPtr(void (* func)(int argument, bool flag))
{
funcPtrTrue = func(argument, true);
funcPtrFalse = func(argument, false);
}
(I now, this is no correct code, but should illustrated the desired functionality)
After Olis proposal, let's complicate things. bool
is a typedef in function.h
:
typedef enum {
FALSE,
TRUE
} bool;
Now I have to include function.h
again to module.c
in order to make it work again.
#include "function.h"
void functionTrue(int argument)
{
fktPtr(argument, TRUE);
}
Upvotes: 1
Views: 2637
Reputation: 43518
you can use structures
struct funcstruct {
void (*func)(int arg, bool flag);
bool default_flag;
} funcstruct;
struct funcstruct funcPtrTrue, funcPtrFalse;
void setFuncPtr(void (* func)(int argument, bool flag))
{
funcPtrTrue.func = func; funcPtrTrue.default_flag = true;
funcPtrFals.func = func; funcPtrFals.default_flag = false;
}
Upvotes: 1
Reputation: 272497
C doesn't have default arguments.
I assume there's some good reason you want two separate function pointers, rather than just directly calling funcPtr
with the required flag
parameter. If so, why not just have two wrapper functions inside your module?
void (* funcPtr)(int argument, bool flag);
void setFuncPtr(void (* func)(int argument, bool flag)) {
funcPtr = func;
}
void funcTrue(int argument) { funcPtr(argument, true); }
void funcFalse(int argument) { funcPtr(argument, false); }
Upvotes: 4