Concept

How can comparator functions order Student structures?

ComputerScienceOne / Comparator Functions

"A comparator function is designed with certain expectations, namely that a user will always pass it valid pointers to values of the expected type. If two double pointers are passed to cmpInt(), the code will not work as intended because it will end up comparing the upper 32 bits of the double values, which leads to unintended behavior. If a user violates these expectations, it is their fault, not ours. This is no different from many other functions in the standard library; passing non-null-terminated strings to most string functions, for example, is undefined behavior.\n\nComparator functions can order Student structures based on one or more of their components. To order students by last name and then first name in alphabetic order, the comparator casts the generic pointers to const Student pointers, compares the last names with strcmp(), and compares the first names if the last names are equal:\n\nint studentByNameCmp(const void *s1, const void *s2) {\n\nconst Student *a = (const Student *)s1;\n\nconst Student *b = (const Student *)s2;\n\nint result = strcmp(a->lastName, b->lastName);\n\nif(result == 0) {\n\nreturn strcmp(a->firstName, b->firstName);\n\n} else {\n\nreturn result;\n\n}\n\n}\n\nA reverse alphabetic ordering can reuse this comparator by flipping the arguments:\n\nint studentByNameCmpDesc(const void *s1, const void *s2) {\n\nreturn studentByNameCmp(s2, s1);\n\n}\n\nStudents can also be ordered by id in ascending numerical order. The comparator casts the arguments to Student pointers and compares their nuid fields:\n\nint studentIdCmp(const void *s1, const void *s2) {\n\nconst Student *a = (const Student *)s1;\n\nconst Student *b = (const Student *)s2;\n\nif(a->nuid < b->nuid) {\n\nreturn -1;\n\n} else if(a->nuid == b->nuid) {\n\nreturn 0;\n\n}"

Related Ideas

How can comparator functions order Student structures? | ComputerScienceOne | Bifalgorithm | Bifalgorithm