Bifalgorithm post · Computer science one · Comparator Functions
How can comparator functions order Student structures?
How can comparator functions order Student structures? (Computer science one · Comparator Functions) — "A comparator function is designed with certain expectat…
Ideas in this flowchart
- Comparator functions order values through generic pointers.
- The caller is expected to provide valid pointers to values of the expected type.
- Violating these expectations causes unintended or undefined behavior.
- Passing double pointers to cmpInt() makes the code compare the upper 32 bits of the double values.
- Incorrect pointer types are the caller’s responsibility, as with many standard-library functions.
- Passing non-null-terminated strings to most string functions is undefined behavior.
- Comparator functions can order Student structures by one or more components.
- studentByNameCmp() orders students alphabetically by last name and then first name.
- The comparator casts the generic pointers to const Student pointers and compares the last names with strcmp().
- When the last names are equal, the comparator compares the first names.
- studentByNameCmpDesc() reuses the name comparator by reversing its arguments.
- studentIdCmp() orders students by their nuid values in ascending numerical order.
- The ID comparator casts the arguments to Student pointers and compares their nuid fields.
- If the first nuid is smaller, the comparator returns -1.
- If the two nuid values are equal, the comparator returns 0.