Question

I have a small program that uses function pointers.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _myst
{
    int a;
    char b[10];
}myst;

void cbfunc(myst *mt)
{
    fprintf(stdout,"called %d %s. \n",mt->a,mt->b);
}

int main()
{

    /* func pointer */
    void (*callback)(void *);

    myst m;
    m.a=10;
    strcpy(m.b,"123");

    /* point to callback function */
    callback = (void*)cbfunc;

    /* perform callback and pass in the param */
    callback(&m);

    return 0;

}

The function pointer decleration

void (*callback)(void*);

declares a function pointer callback that takes a generic-pointer and returns void.

While assigning cbfunc to callback

callback = cbfunc;

I get the warning

warning: assignment from incompatible pointer type [enabled by default]

If I use the following

callback = (void*)cbfunc;

It compiles without any warnings.I am using gcc (4.6.3) and compiling with CFLAGS=-g -O3 -Wall

Can someone explain the reason for this?

Was it helpful?

Solution 2

Why does the assignment generate a warning?

You have a super power: you can make friends with any dog. You are put into a box that says "the person in this box can make friends with any animal". Then someone puts a tiger in your box. How's your day going now?

Now do you see why the assignment is a warning? You have a method that states it can accept any pointer to myst and you are putting it in a box that says "the function pointed to by this pointer can accept a pointer to anything". That's potentially dangerous; what's stopping the user of that function pointer from passing a pointer to a tiger into the function?

Why does the compiler suppress the warning when there is a cast?

Because that's the purpose of a cast. A cast operator means "compiler, I know the thing I am doing is crazy dangerous but I mean to do it and know it will work, so stop giving me warnings and errors about this crazy conversion". Casts effectively turn off the safety system. If that's not what you mean to do then don't write a cast.

OTHER TIPS

Change void (*callback)(void *); to void (*callback)(myst *);, since this is what your function actually is.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top