Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
207 views
in Technique[技术] by (71.8m points)

c++ - function pointers with void* argument casting

I have no idea on how to look this up, even the title is confusing, even I am confused about what I'm looking for, and the question has for sure already been asked but it's so specific to be found, so here a bit of context:

int comparison(const int* a, const int* b) {
    return *a - *b;
}

int main(int argc, char const *argv[])
{
    int arr[3] = {1,6,-2};
    qsort(arr,3,sizeof(int),comparison);
    return 0;
}

Well, it does work, but the compiler gives me a warning, because qsort wants a function of type:

int(*)(const void*, const void*) 

and comparison is a function of type:

int(*)(const int*, const int*) 

I want to know why the compiler is not happy because it just has to cast the address. It should even be happy to give a type to a void* pointer. Is this really bad? Like an undefined behavior or something? Or just the compiler whining about nothing much?

question from:https://stackoverflow.com/questions/66057536/function-pointers-with-void-argument-casting

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

why he (the compiler) is not happy .

qsort() expects a function point of type int (*)(const void *a, const void *b), not int (*)(const int *a, const int *b). The compiler could guess its OK and beform a cast, yet it is more productive for the compiler to warn about such problems.

Or just the compiler whining about nothing much?

By warming you, you are allowed to determine the degree of the problem.


In addition to @Alex Reynolds good answer, note that *a - *b may overflow, resulting in the wrong comparison.

Instead:

int comparison(const void *a, const void *b) {
  const int *ia = (const int *)a;
  const int *ib = (const int *)b;
  return (*ia > *ab) - (*ia < *ib);
}

Good compilers recognize the (p>q) - (p<q) idiom and emit efficient code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...