Вопрос

I wonder, when we create the function

int compar(const void *, const void *)

and we merely pass its name into one of the parameters of qsort and bsearch, how do those functions recognize said essentially random word (since we've never explicitly stated it is a function pointer, but rather an actual function) and use it as a parameter? Is there an explicit cast in the function declarations of qsort and bsearch or something?

Это было полезно?

Решение

This has nothing to do with the qsort and bsearch functions themselves, rather function names are implicitly converted by the compiler into function pointers as per the standard, C11 6.3.2.1 Language / Conversions / Other operands / Lvalues, arrays, and function designators:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator, the _Alignof operator, or the unary & operator, a function designator with type "function returning type" is converted to an expression that has type "pointer to function returning type".

That means that, when you pass compar to qsort() (for example), it's the actual pointer to the function that gets passed, not some "essentially random word".


The reasons for implicitly treating a function identifier as its address lie long ago in the past but (and this whole section is supposition on my part, based on what I'd like to consider intelligent reasoning, but in no way definitive) it's likely to be because the value of a function makes no sense. With an identifier int i = 5;, it has a value (5), and you can also use &i to get it's address.

However, for functions, they don't really have values as such. You can call them to generate a value, xyzzy(), and you can get their address, &xyzzy, for later calling via a function pointer.

But they have no real intrinsic value separate from their address like the integer i does. So early compilers (pre-ANSI) simply allowed the shorthand xyzzy to mean &xyzzy. And, of course, since the original mandate of ANSI was to codify existing practice rather than create a new language, they preserved this behaviour.

If K&R had gone the other way and decided xyzzy should be a call to the function passing no parameters, the same as xyzzy(), the world would be a different place :-)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top