Hi Gero,
On 2026-02-19T03:48:43+0100, Gero Treuner wrote:
> On Thu, Feb 19, 2026 at 01:57:11AM +0100, Alejandro Colomar via Mutt-dev
> wrote:
> > > > char *
> > > > strchrnul(const char *s, int c)
> > > > {
> > > > char *p;
> > > >
> > > > p = strchr(s, c);
> > > > if (p == NULL)
> > > > return (char *) s + strlen(s);
> > > > return p;
> > >
> > > This can be compacted into a one-liner:
> > >
> > > return strchr(s, c) ?: (char *) s + strlen(s);
> >
> > And avoiding the cast:
> >
> > #define strnul(s) strchr(s, '\0')
> >
> > char *
> > strchrnul(const char *s, int c)
> > {
> > return strchr(s, c) ?: strnul(s);
> > }
>
> On compiler level this replaces a function with 1 argument by
> another with 2 (although functionally equivalent).
>
> Personally I don't have an issue with casts.
Casts are dangerous, and hurt readability.
> But I do care about the
> footprint on the end users system (even if the difference is small).
The optimization is so trivial that gcc -O1 produces the same assembly
for both:
alx@devuan:~/tmp$ diff -u strchrnul*.c
--- strchrnul1.c 2026-02-19 10:56:48.787467463 +0100
+++ strchrnul2.c 2026-02-19 10:56:51.924802397 +0100
@@ -1,6 +1,8 @@
#include <string.h>
+#define strnul(s) strchr(s, '\0')
+
char *
strchrnul(const char *s, int c)
{
- return strchr(s, c) ?: (char *) s + strlen(s);
+ return strchr(s, c) ?: strnul(s);
}
alx@devuan:~/tmp$ gcc -S -O1 strchrnul*.c
alx@devuan:~/tmp$ diff -u strchrnul*.s
--- strchrnul1.s 2026-02-19 10:57:26.787769644 +0100
+++ strchrnul2.s 2026-02-19 10:57:26.799769740 +0100
@@ -1,4 +1,4 @@
- .file "strchrnul1.c"
+ .file "strchrnul2.c"
.text
.globl strchrnul
.type strchrnul, @function
Have a lovely day!
Alex
--
<https://www.alejandro-colomar.es>
signature.asc
Description: PGP signature
