Enslaved Mortal
Enslaved Mortal

Reputation: 11

callback function is having issue with void expression in C?

I am learning the basics of Function pointer in C and their calls backs. But I am stuck due to line 15. The source won't compile. Compiler says

In function ‘main’: error: invalid use of void expression @ call_fun(displayMessage(Message))

#include <stdio.h>

void displayMessage( void * string){
printf("%s\n", (char*)string);
}

//function pointer as argument
void call_fun (void (*funPtr)()) {
displayMessage(); // call Back function that funPtr points out to 
}

int main(){
char * Message = " Hello World";
call_fun(displayMessage(Message));
return 0;
}

Thank you all in advance

Upvotes: 0

Views: 211

Answers (1)

John Bollinger
John Bollinger

Reputation: 180093

This ...

void (*funPtr)()

... declares funPtr as a pointer to a non-variadic function accepting an unspecified number of arguments of unspecified type, and returning void.

This ...

displayMessage(Message)

... is a function call, whose type, in your case, is void. The types void and void (*funPtr)() are not compatible.

Presumably, you want to pass a pointer to displayMessage instead of the result of calling displayMessage. For the former, just use the function name:

call_fun(displayMessage);

But you will quickly notice that the message itself does not appear in that expression, and this is a problem if you want the code that calls call_fun to specify the message to pass to displayMessage. To enable that, you would need to pass the message as a separate parameter, or come up with some other means to convey it to call_func.*

You should consider also function call_fun(). You should recognize that it declares parameter funPtr but never references it. You should also recognize that it explicitly calls displayMessage() (with the wrong number of parameters), which doesn't make sense if its caller is supposed to be the one specifying what function to call. Additionally, although it is allowed to declare a function pointer that does not provide a prototype, it is almost always better for function pointers to be declared with prototypes.

Overall, then:

#include <stdio.h>

void displayMessage(const char *string) {
    printf("%s\n", string);
}

//function pointer as argument
void call_fun (void (*funPtr)(const char *), const char *message) {
    funPtr(message); // call the function that funPtr points out to 
}

int main(void) {
    const char *Message = "Hello World";
    call_fun(displayMessage, Message);
    return 0;
}

* However, a more typical callback scenario is for one component to specify the (callback) function to a different component that chooses the timing of and arguments to the calls.

Upvotes: 1

Related Questions