Confusing statement in the C function declaration

132 views Asked by At

I am going through a code implementation of USB drivers on an STM32 MCU. My C language understanding is a bit limited and I have come across this function definition that is not clear to me.

static enum usbd_request_return_codes cdcacm_control_request(
usbd_device *usbd_dev __attribute__((unused)),
struct usb_setup_data *req,
uint8_t **buf __attribute__((unused)),
uint16_t *len,
void (**complete)
    (
        usbd_device *usbd_dev,
        struct usb_setup_data *req
    ) __attribute__((unused))
)

I don't understand the last argument in the function declaration where it seems like it is actually defining another function for the argument and takes weird two asterisks as parameter. Could somebody explain what is this and how it might be used in the actual function call?

1

There are 1 answers

5
Vlad from Moscow On BEST ANSWER

This

void (**complete)
    (
        usbd_device *usbd_dev,
        struct usb_setup_data *req
    ) __attribute__((unused))

is a declaration of a pointer to function pointer. The function has the return type void and two parameters.

To make it more clear consider the demonstrative program below.

#include <stdio.h>

void f( int x, int y )
{
    printf( "x + y = %lld\n", ( long long int )x + y );
}

void g( int x, int y, void ( **fp )( int, int ) )
{
    ( *fp )( x, y );
}

int main(void) 
{
    void ( *fp )( int, int ) = f;
    
    g( 10, 20, &fp );
    
    return 0;
}

The program output is

x + y = 30

Without a more broad context it is difficult to say why a pointer to pointer to function is used. Maybe it is due to that the parameter is an output parameter. Or there can be a dynamically allocated array of pointers to functions.