user2630165
user2630165

Reputation: 311

Pointer to functions in C

Is this syntax correct?

cmp is a pointer to a function. Everything in my program works ok, BUT :

  1. look ! I didn't use * when I declared cmp in the function. Why does my code work?
  2. When I declare it with int (*cmp) everything also works great.

What is going on here ??

RangeTreeP createNewRangeTree(Element participateWorkers[], int arrsize,
                              int cmp(ConstElement, ConstElement))

Shouldn't it be:

RangeTreeP createNewRangeTree(Element participateWorkers[], int arrsize,
                  int (*cmp)(ConstElement, ConstElement))

?

The call to this createNewRangeTree function is :

createNewRangeTree(tempArr, NUM_PAR, &teacherCmpSalary)

and teacherCmpSalary is a regular function that looks like this :

int teacherCmpSalary(ConstElement c1, ConstElement c2)

Upvotes: 1

Views: 106

Answers (1)

Keith Thompson
Keith Thompson

Reputation: 263177

Either form is correct.

If you define a function parameter that's of function type, as in your first example, it's automatically "adjusted" to be of the corresponding pointer-to-function type.

There's a very similar rule for array parameters; your parameter Element participateWorkers[] is exactly equivalent to Element *participateWorkers.

(Both of these rules apply only to parameter declarations, not in other contexts.)

Reference: N1570 (the most recent draft of the 2011 ISO C standard), section 6.7.6.3, paragraphs 7 (for arrays) and 8 (for functions).

It's not possible to have parameters of array or function type, so the syntax is "borrowed" for parameters of the corresponding pointer types.

Personally, I prefer to use the pointer notation because it's more explicit, but you should at least understand both forms, since you're going to see them both in other people's code.

Upvotes: 2

Related Questions