qsort: Cast the comparator function itself or the parameters in the body of comparator function?

You should avoid the latter case because it’s not valid.

For two function types to be compatible, the return types must be compatible and the corresponding parameter types must be compatible. A const void * is not compatible with a const double * therefore the function types are not compatible. Calling a function through an incompatible pointer type results in undefined behavior.

Note that just because two types may be implicitly converted doesn’t mean they are compatible. Taking the example of const double * and const void *, conversion between the two types can be performed without a cast, however the representation of the two types need not be the same.

This means that the way a const double * is passed to a function may be different from how a const void * is passed to a function. So by calling a function of type int (*)(const double*, const double*) as if it had type int (*)(const void*, const void*), the parameters could be passed in an incorrect way.

While x64 and ARM systems will typically use the same representation for all pointer types, you might get away with doing the former, but there’s still no guarantee of that. Modern compilers will often assume undefined behavior will not happen and perform optimizations based on that fact.

The former case is the proper method as the function’s signature is compatible with what the qsort function expects.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)