-1

I am looking into some C code for a microcontroller. I understand most of the code however this piece of the code is puzzling me. I am also including relevant definitions for used data types. I have substituted function and variable names for the ease sake.

#define COUNT           (2)    
typedef void(*some_type)(void *p);
some_type       some_arr[COUNT] = {NULL, };            

void init(void)
{
    first_function(&second_function);
}

void first_function(some_type cb)
{
    if(some_arr_count < COUNT)
    {
         some_arr[some_arr_count++] = cb;
    }
}

void second_function(void *p)
{
    another_type *req;
    req = (another_type *)p;
    //some other code goes here
}

1.What does this typedef means?

typedef void(*some_type)(void *p);

init() function gets called only once and it has only one line of code.

2.What does this line do?

first_function(&second_function);

I searched for the term second_function in the entire project code and it this the only place it appears besides function definition.

3.So how does second_function get called?

Jigar Patel
  • 4,585
  • 1
  • 17
  • 20

2 Answers2

1

Firstly, as suggested in the comments you should go read about function pointers. I got this (How do function pointers in C work?) from a Google search.

The above link should help to explain answers to question 1 and 2. For question 3, it is likely that the micro-controller has some built-in mechanism or library function which calls all the function call-backs in some_arr[COUNT], something like the following might work (untested):

for (int i = 0; i < COUNT; ++i)
{
    if (some_arr[i] == NULL) break;
    (*some_arr[i])(&something_useful);
}

Where something_useful would be some sort of data that the call-back function could use.

If you are able to search the library code for uses of some_arr you might find code to call the second_function (although it will no longer be called second_function).

Community
  • 1
  • 1
ilent2
  • 5,171
  • 3
  • 21
  • 30
1
  1. The following typedef

    typedef void(*some_type)(void *p);
    

    will define some_type as a pointer to function of type void ()(void *).

  2. The following statement

    first_function(&second_function);
    

    is a function call, &second_function, which is the address of second_function , is the argument to first_function().

  3. The function second_function could be called like this

    some_arr[some_arr_count](p);
    

    some_arr[some_arr_count] is a function pointer to second_function, which is assigned in first_function, and p is the argument of second_function, which is a pointer to void.

Lee Duhem
  • 14,695
  • 3
  • 29
  • 47