Reputation: 841
I'm aiming to use qsort from stdlib.h. qsort requires a comparison function argument fulfilling this:
int (*compar)(const void *, const void*)
Am I right reading this as, "a pointer to an int-returning function f. f must take two arguments which are generic pointers"? I'm not certain of the meaning of the brackets around '*compar' - is there a name for this I can look up?
The link provides an example:
int cmpfunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
Would I be right reading *(int*)a as "dereferencing the value of a, after it has been cast as a pointer to an integer"?
Cheers.
Upvotes: 3
Views: 138
Reputation: 385829
Am I right reading this as, "a pointer to an int-returning function f. f must take two arguments which are generic pointers"?
Exactly right.
I'm not certain of the meaning of the brackets around
*compar
That's the syntax for declaring pointers to functions (which are called "function pointers"). Without the parens, it would be a function declaration
// Declares a function named compar. (It returns an int*.)
int *compar(const void *, const void*);
// Declares a function pointer named compar. (The func returns an int.)
int (*compar)(const void *, const void*);
Would I be right reading
*(int*)a
as "dereferencing the value of a, after it has been cast as a pointer to an integer"?
Correct again. It gives the int
at address a
.
Upvotes: 8
Reputation: 134336
You're in right path.
In your first example, compar
is called a Function pointer. The ()
are the part of the syntax of a function pointer.
Please, note, without the explicit ()
around *compar
, compar
will be treated as a fucntion returning an int *
, accepting two void
pointers.
For the second case, , for the binary subtraction operator -
, from the C99
standard, chapter 6.5.6, paragraph 3,
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible object types; or
— the left operand is a pointer to an object type and the right operand has integer type. (Decrementing is equivalent to subtracting 1.)
and for the first point, the arithmatic type
, from chapter 6.2.5, paragraph 18,
Integer and floating types are collectively called arithmetic types.
So, here, before using the pointers for subtraction, they are casted to int
pointer, then dereferenced and the value(s) is(are) used as the operands for integer subtraction.
Upvotes: 4
Reputation: 106012
Yes. You are understanding right both of the syntax. The brackets ()
around *compar
means that compar
is function pointer. In absence of it the meaning will be completely different.
Upvotes: 1