Reputation: 1374
I've just came up with this code on minute 1:06 of a coursera lecture. What does it do?
int (*cmp)(char*, char*);
Upvotes: 4
Views: 423
Reputation: 190
The code you have pasted is actually a pointer to a function. the prototype of the function could be:
int cmp (char*, char*);
There are three parts in this function: the return type is an integer, the name of the function is cmp
and there are two arguments, all of which are a pointer to a character (array). Specifically, the function is used for sorting, for example, if the first argument is less than the second one, the function will return a negative number, if equal, return zero, and if greater, return a positive number. For example, if I have the following code:
char c1 = 'a';
char c2 = 'b';
int result = cmp(&c1, &c2);
Then The result will be a negative number, e.g. -1, because 'a' is less than 'b'. In the function call above, I added & before each argument, because the argument data type are pointers/references to the character. &
is an operation to get the address of the variable.
With regards to the code you've provided, there is actually an additional *
before the name of the function cmp
. That means you want to get the reference of the entire function, rather than any single variable or array. For example, the following is the prototype of the function qsort in C:
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
The third argument of this function is actually very similar to the code you have provided. The reason to do so is you can directly pass a whole function to another function, e.g., qsort, as an argument.
Take a look at of this link for details about pointers in C.
I hope this answers your question.
Upvotes: 1
Reputation: 30916
This is a pointer to a function where the function returns an int and takes as argument two character pointers.
The basic rule boils down to few things:-
There are three simple steps to follow:
[X] or []
X
size of... or Array undefined size of...(type1, type2)
type1
and type2
returning...
*Reference: 1.Clockwise-rule 2.right-left rule
Upvotes: 10
Reputation: 15783
When you read C declarations you must read them butrophedonically (common way of writing in stone in Ancient Greece).
pointer to
function that
has (char*, char*) type parameters as input
and int as output
EDIT:
Upvotes: 6