user1086516
user1086516

Reputation: 877

is this a void pointer? casting? what is it doing?

I am new to the C language and pointers and I am confused by this function declaration:

void someFunction(int (*)(const void *, const void *));

Can anyone explain in layman's terms what this does and how it works?

Upvotes: 1

Views: 230

Answers (5)

FourOfAKind
FourOfAKind

Reputation: 2418

Check this very helpful when dealing with complex declarations.

Upvotes: 0

James Eichele
James Eichele

Reputation: 119164

This is the declaration of a function which takes a function pointer as its argument. In its most basic form, it looks like this:

void someFunction(argument_type);

Where argument_type is int (*)(const void *, const void *), which can be described as a "pointer to a function that takes two const void * arguments, and returns an int". i.e. any function that has the following declaration:

int foo(const void *, const void *);

To illustrate by example:

int foo_one(const void * x, const void * y) { ... }
int foo_two(const void * x, const void * y) { ... }

void someFunction(int (*)(const void *, const void *) function_ptr)
{
    const void * x = NULL;
    const void * y = NULL;
    int result;
    result = (*function_ptr)(x, y); // calls the function that was passed in
}

int main()
{
    someFunction(foo_one);
    someFunction(foo_two);
    return 0;
}

Upvotes: 0

Rob K
Rob K

Reputation: 8926

It declares a function, which takes another function as its argument, and returns nothing. The other function would be declared as

int otherfunction( const void *, const void * );

and you would call somefunction() like this:

somefunction( otherfunction );

Upvotes: 2

Chris Smith
Chris Smith

Reputation: 5454

It's a function that has a single parameter. That parameter is a pointer to a function that returns an int and takes those two void pointers to constant data parameters.

Upvotes: 0

Seth Carnegie
Seth Carnegie

Reputation: 75150

It's the prototype of a function that takes:

a pointer to a function that takes a const void* and a const void* as arguments and returns an int

as an argument, and returns void.

Upvotes: 3

Related Questions