Originally Posted by
Snafuist
I can't see any reason for not comparing the struct member for member, as in x.m1==y.m1, x.m2==y.m2 and so on. On a sidenote, it's certainly not possible to write a generic struct comparing function.
Of course it is. You can construct a list of elements of an object, and write a generic function that compares two structures arbitrarily according to some generic rules. A structure like this would work:
Code:
typedef { VOID = 0, INT, STR, CHAR, CHARPTR, FLOAT, DOUBLE } EType;
typedef struct SElement
{
char *name; // Not actually needed - just because the macro CAN DO THAT.
offset_t offs;
enum EType type;
} Element;
typedef struct SExample
{
int a;
char *str1;
char str2[40];
char b;
} Example;
#define ELEM(structname, name, type) { #name, offsetof(structname, name), type }
Element ExampleDescr [] =
{
ELEM(Example, a, INT),
ELEM(Example, str1, CHARPTR),
ELEM(Example, str2, STR),
ELEM(Example, b, CHAR)
};
int CompareStructsGeneric(void *struct1, void *struct2, Element descr, size_t nElements)
{
for(i = 0; i < nElements; i++)
{
switch(descr[i].type)
{
case INT:
if (*(int *)((char*)struct1+descr[i].offset) > *(int *)((char*)struct2+descr[i].offset)
return 1;
else if (*(int *)((char*)struct1+descr[i].offset) < *(int *)((char*)struct2+descr[i].offset)
return -1;
break; /* Equal, continue to next element ... */
....
}
}
return 0;
}
Obviously, we'll need to make suitable pointer arithmetics to figure out the rest of the functions.
But you could certainly use this mechanism to compare completely arbitrary structures, as long as they are both the same type.
--
Mats