1

I started working on this C project and I found this weird code that I have never seen any thing like !

cas_send_browser_event_cb(cas_browser_event_t ev, void* priv)
   {
      Function_code ...
   }

As you can see this function take two arguments , the first one is an enum and the second is void *.

I look for the call of this function and I find this :

casware_register_cb_uievent (cas_send_browser_event_cb , NULL);

As you can see, it is passed as a parameter to another function without arguments and even without (). I can't understand this code. Am I missing something ? (well it is somehow related to event programming).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
HobbitOfShire
  • 2,144
  • 5
  • 24
  • 41
  • 1
    it is passing a pointer to the function `cas_send_browser_event_cb` – isedev Sep 30 '14 at 08:29
  • 1
    It looks like `casware_register_cb_uievent` takes a pointer to a function of the same type that `cas_send_browser_event_cb` is, so the first argument to `casware...` decays to that pointer. The function will probably only be called later via its pointer. – Niall Sep 30 '14 at 08:29
  • first, mandatory, obvious step: check the defintion/declaration of `casware_register_cb_uievent` – Karoly Horvath Sep 30 '14 at 08:34

2 Answers2

4

casware_register_cb_uievent (cas_send_browser_event_cb , NULL);

is passing a pointer to the function casware_register_cb_uievent

To understand a little more consider the following code.

#include<stdio.h>


void hello()
{
        printf("hello world");
}

void world(void (*fun)())
{
         fun();
}

main()
{
        world(hello);
}

Here the function world is similar to the function casware_register_cb_uievent

void world(void (*fun)()) the function world accepts a pointer to a function which is pointed by fun

now when the function hello (similar to the function cas_send_browser_event_cb) is given as input it is similar to assining the pointer as

fun = hello

the function call

fun() in world calls the function pointed by it, hello producing output as

hello world

when a function is declaread as

void (*fun)(); a function pointer is created.

The function pointer can be assigned using name of another function to which it is to be pointed

fun = hello;

now on calling the pointer, fun the function being pointed, hello is intern called

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1

It's a function pointer that's being passed, that's likely been typedef-ed. This means that the location of the case_send_browser_event is being passed, so that it can alter the behavior of the casweare_register_cb_uievent function.

This kind of passing is very helpful in algorithms where you'd want to maximize for different things on the fly, so changing the Boolean function used to do a compare from a minimize to a maximize would provide opposite behavior for a sort algorithm.

Community
  • 1
  • 1
Yann
  • 978
  • 2
  • 12
  • 31