COMPARE(3pub)

πŸ’– COMPARE(3pub) β€” comparison functions, but make it bestie-coded

okay so this is a page from the C Programmer's Manual (the 3pub section, iykyk) and it's literally just a whole squad of tiny comparison functions that exist so qsort, bsearch and the rest of that friend group can sort your stuff without you writing the same boring if chain eleven times. no cap. let's go πŸ¦‹


✨ NAME ✨

cmp_set_offset, cmp_struct, cmp_char, cmp_short, cmp_int, cmp_long, cmp_float, cmp_double, cmp_long_double, cmp_schar, cmp_uchar, cmp_ushort, cmp_uint, cmp_ulong, cmp_charptr, cmp_chararr β€” comparison functions for qsort, bsearch, and others πŸ’…

πŸŽ€ SYNOPSIS πŸŽ€

#include <cmp.h>
void cmp_set_offset(size_t offset, int (*)(const void *, const void *));
int cmp_struct(const void *, const void *);

int cmp_char(const void *, const void *);
int cmp_short(const void *, const void *);
int cmp_int(const void *, const void *);
int cmp_long(const void *, const void *);
int cmp_float(const void *, const void *);
int cmp_double(const void *, const void *);
int cmp_long_double(const void *, const void *);

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

int cmp_uchar(const void *, const void *);
int cmp_ushort(const void *, const void *);
int cmp_uint(const void *, const void *);
int cmp_ulong(const void *, const void *);

int cmp_charptr(const void *, const void *);
int cmp_chararr(const void *, const void *);

🌸 DESCRIPTION 🌸

so. every function up there except cmp_set_offset does the same little trick: you hand it two pointers to array elements of the type its name is screaming about, and it compares those two elements for you. that's it. that's the whole vibe. 🫢

they're built to slot straight into qsort(3), bsearch(3), and a bunch of other library functions that all want that exact same flavor of comparison function. the contract is the classic one, fr fr:

  • negative if the value pointed to by the first argument is less than the second
  • 0 if they're the same
  • positive otherwise

cmp_struct is the special one, bestie β€” it compares elements of a structure πŸ‘‘. it needs two things from you: the offset of the element inside the struct, and a comparison function that actually fits the type of that element. you set both of those with cmp_set_offset, and you gotta call it before qsort(3) or it's giving nothing. and the settings? they stick around until you change them. periodt. πŸ’€

πŸ’œ SEE ALSO πŸ’œ

⭐ AUTHOR ⭐

Lars Wirzenius (lars.wirzenius@helsinki.fi) β€” icon behavior, we love to see it πŸ’–


and that's the whole page, babes ✨ this little gem lives in Publib, filed under the C Programmer's Manual as COMPARE(3pub). mwah, go sort something πŸŽ€πŸ’…

πŸ“¦ where this page comes from