简体   繁体   中英

Possible to pass a non-void function pointer as a void function pointer?

Say I have a function foo() which accepts a pointer to a void function as a parameter.

void foo(void (*bar)(int)) {
    bar(5);
}

If I have a non- void function f(int)

bool f(int i) {
    // ...
    return true;
}

Is there a way to cast f in such a way that it can be passed to foo() without warnings?

My current solution is to define a function void g(int i) {f(i);} and pass g to foo , but this seems inefficient to me. It seems like there should be a way to cast f in such a way that its return value is thrown out.

If this isn't possible, why not?

Sorry if I'm missing the point, but this compiles without warnings with gcc , even with -Wall :

typedef void (*p_bar) (int);

void foo (p_bar bar)
  {
  bar(5);
  }

int f (int i)
  {
  printf ("In f(), arg=%d\n", i);
  return 1;
  }

int main() 
  { 
  foo ((p_bar)f);
  }

I can see why this is a suspicious cast but, in fact, I suspect that it will work fine for integers on most modern compilers. Integers are nearly always returned in a register.

But, as I say, maybe I'm missing something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM