Tim
Tim

Reputation: 99438

Passing a value into a function without being listed as a formal argument?

In stdlib.h,

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

will it be possible to pass the following function as compar,

int compareMyType (const void * a, const void * b, float c)
{
  float tmp = f((MyType*)a,  (MyType*)b, c );  // f is some function
  if (tmp < 0) return -1;
  if (tmp == 0) return 0;
  if (tmp > 0) return 1;
}

If no, without declaring c to be a global variable, is there some way? Thanks!

Upvotes: 0

Views: 63

Answers (3)

Crozin
Crozin

Reputation: 44386

Create a proxy-function that will be compatible with qsort and in its body it will call your function:

int myCompare(const void *a, const void *b) {
    float c = ...;

    return compareMyType(a, b, c);
}

...

qsort(..., myCompare);

Upvotes: 3

ajay
ajay

Reputation: 9680

will it be possible to pass the following function as compar

No. Pointers to functions with only the exact same signatures are compatible. Your compar function must have the signature

int compar(const void *, const void *);

You can write your own qsort function with custom compar function prototype or you can encapsulate your compare function of different signature within a function of the above signature which simply calls your compare function.

Upvotes: 0

user3497792
user3497792

Reputation:

No, function signature doesn't match. compareMyType (const void * a, const void * b, float c) and int (compar)(const void,const void*)

You can pack the variable c in structure and typecast the structure pointer to void pointer and pass it. That is the main advantage of using void pointer in the first place.

Upvotes: 0

Related Questions