]> git.ipfire.org Git - thirdparty/man-pages.git/commitdiff
bsearch.3: EXAMPLES: Use ARRAY_SIZE()
authorAlex Colomar <alx.manpages@gmail.com>
Sat, 10 Sep 2022 21:45:37 +0000 (23:45 +0200)
committerAlex Colomar <alx.manpages@gmail.com>
Mon, 12 Sep 2022 15:08:24 +0000 (17:08 +0200)
This is more generic code, and hopefully, it will inspire other to
use such a pattern.

Signed-off-by: Alex Colomar <alx.manpages@gmail.com>
man3/bsearch.3

index cf5fa7a0abb7ca284a1ce944b355fe6d9bd2138d..dbb0a2fa540fcd7ec2f803544d4b492186f8349e 100644 (file)
@@ -88,6 +88,8 @@ then retrieves desired elements using
 #include <stdlib.h>
 #include <string.h>
 
+#define ARRAY_SIZE(arr)  (sizeof((arr)) / sizeof((arr)[0]))
+
 struct mi {
     int         nr;
     const char  *name;
@@ -99,8 +101,6 @@ static struct mi  months[] = {
     { 9, "sep" }, {10, "oct" }, {11, "nov" }, {12, "dec" }
 };
 
-#define nr_of_months (sizeof(months)/sizeof(months[0]))
-
 static int
 compmi(const void *m1, const void *m2)
 {
@@ -112,13 +112,13 @@ compmi(const void *m1, const void *m2)
 int
 main(int argc, char *argv[])
 {
-    qsort(months, nr_of_months, sizeof(months[0]), compmi);
+    qsort(months, ARRAY_SIZE(months), sizeof(months[0]), compmi);
     for (int i = 1; i < argc; i++) {
         struct mi key;
         struct mi *res;
 
         key.name = argv[i];
-        res = bsearch(&key, months, nr_of_months,
+        res = bsearch(&key, months, ARRAY_SIZE(months),
                       sizeof(months[0]), compmi);
         if (res == NULL)
             printf("\(aq%s\(aq: unknown month\en", argv[i]);