I assumed that the following function can get any datatype such as float, double, long, and long long and return a correct answer. Unfortunately, it does not. Can anyone explain why? My aim is to create a generic "less than" and implement something similar to
int le_generic(const void* a, const void* b){
return *(long long*) < void *(long long*)b;
}
PS:
I have tried the suggested below:
void *aptr1, =const &m->data[m->heap[i]];
void *b = &m->data[m->heap[j]];
double c = m->data[m->heap[i]];
double d = m->data[m->heap[j]];
printf("%d, %d\n", le_generic(*a,* *b)ptr2, csize_t <num d);
but with
#define le_generic(a,b) ((a)<(b))
Your code can not work because different data types uses different machine representations.
Defining int le_generic(const void* a, const void* b)
lets you call that function with pointers to any data type. This violates the standard constraints on comparing elements of the same type alas with your definition:
int a;
double b;
le_generic(&a,&b);
is an acceptable call.
Worst is *(long long*)a < *(long long*)b
which assumes that what you pass is necessarily pointers to long long
, which is never the case except in one case:
long long a, b;
le_generic(&a,&b);
There is no genericity in C. You can not define a generic function. My workaround would be to define a macro, which is roughly a syntactic replacement. When you define:
#define le_generic(a,b) ((a)<(b))
that means that everywhere you use le_generic(sometext,othertext)
the compiler will replace it with the exact expression ((sometext)<(othertext))
.
You can then use it like this:
int i1, i2;
le_generic(i1,i2);
float f1, f2;
le_generic(f1,f2);
etc. Alas there is then no type checking; that is the problem with macros.
Of course you can not use void
too. Looks like you are mistakenly confusing void
and void *
. void
is a type with no value. You can not declare a variable of void
type, nor try to manipulate void
value (there is no). void *
is a type of all possible addresses, it is a type that has values! That type is wrongly sometimes called the generic pointer type (should be better called the supertype of all pointer types), that may be the source of your confusion. There is no genericity (in your meaning) there. When you try to dereference a void *
you get a void
then no value!