Reputation: 21
I need a macro which simply calls the function which is passed as parameter to that macro. The function is void type with no parameter.
For example, if I have the following function:
void function(void) {
//doSomething
}
I need a macro, APPLY_FUNCTION which is called with the function parameter and simply calls that function:
APPLY_FUNCTION(function);
I've tried to define the macro like:
#define APPLY_FUNCTION(function) (function)
But it does not work, when I try to call the macro I am getting a "statement with no effect" error.
The question is how should I define that macro?
Upvotes: 0
Views: 842
Reputation: 213306
The quick & dirty version is simply this:
#define APPLY_FUNCTION(function) (function)()
where the ()
on the end means that this is a function call.
I would however prefer to use a type safe C11 version instead:
#define APPLY_FUNCTION(function) _Generic((function), void (*)(void): (function)())
This prevents the user from passing the wrong kind of function to the macro.
Upvotes: 1
Reputation: 50778
You probably want this:
#include <stdio.h>
#define APPLY_FUNCTION(functionname) functionname()
void function(void) {
printf("Function called\n");
}
int main()
{
APPLY_FUNCTION(function);
}
Output:
Function called
With your definition:
#define APPLY_FUNCTION(function) (function)
The preprocessor generates following line:
(function);
This is syntaxically correct, but it doesn't call the function, hence the warning.
BTW: you should call the macro rather CALL_FUNCTION
. You don't apply a function, you call it.
Upvotes: 1