On Sat, Feb 21, 2026 at 1:38 AM Bruno Haible via Gnulib discussion
list <[email protected]> wrote:
> strchr is a red herring, because this way to define strnul is compiled
> less efficiently than (s + strlen (s)). See attached example code.
>
> The better way is thus (s + strlen (s)), and since it evaluates s twice,
> it means we need an inline function, not a macro. But we have the machinery
> for inline functions in Gnulib.

Maybe it would be a good idea to suggest an update to the glibc manual,
because it says that strchr(s, '\0') is faster than s + strlen(s):

> One useful, but unusual, use of the strchr function is when one wants to have 
> a
> pointer pointing to the null byte terminating a string. This is often written 
> in this way:
>
>  s += strlen (s);
>
> This is almost optimal but the addition operation duplicated a bit of the work
> already done in the strlen function. A better solution is this:
>
>  s = strchr (s, '\0');
>
> There is no restriction on the second parameter of strchr so it could very 
> well
> also be zero. Those readers thinking very hard about this might now point out
> that the strchr function is more expensive than the strlen function since we
> have two abort criteria. This is right. But in the GNU C Library the
> implementation of strchr is optimized in a special way so that strchr
> actually is faster.

(See, e.g. 
https://sourceware.org/glibc/manual/latest/html_node/Search-Functions.html)

Reply via email to