Confirming Jonathan note - my original post was to identify potential
errors - problems. Getting O(n^2) is a serious issue - similar to
"unused-value" - "set-and-not-used" - code that need to be reviewed, looked
at.
There are few cases here:
* If s is read-only (const char *, restricted, ...) - almost always an
error. Good compiler may actually factor out the strlen into a constant.
* If s is read-write - but the body of the code does not modify *s - same
as above.
* There are other cases - where *s is modified- but not in a way that will
add NULL characters.

Even when there was cases where the string is modified - it was (almost)
always possible to rewrite the code in which the len is recalculate when
the string length is modified - e.g., when processing substring
substitution, etc.

An approach where the check is "trigger" happy - (if enabled with -W), and
then the developer can annotate the few cases where it's valid with
#pragama GCC diagnostic .... To some extent this is similar to the current
approach toward "fallthru", where by default, it's assumed to be potential
issue.

#pragma GCC diagnostic ignore "slow-condition"
for ( ... ; strlen(x) ; ... ) { }

Hope it make sense/clearify.

Yair

On Mon, Sep 22, 2025 at 4:31 PM Jonathan Wakely <[email protected]>
wrote:

> On Mon, 22 Sept 2025 at 10:49, U.Mutlu <[email protected]> wrote:
> >
> > Yair Lenga via Gcc wrote on 09/22/25 08:29:
> > >
> > > I've inherited an old code base of "C" code, which was maintained by
> > > relatively inexperience team. One of the common pattern that I've seen
> was:
> > >
> > > for (int i=0 ; i < strlen(s) ; i++) { ... }
> >
> > Such code implies that the string can change between the loop iterations.
> > This of course is a legit use case.
> >
> > If the string is not changing, then the programmer instead should use:
> >    for (size_t len = strlen(s), i = 0; i < len; ++i) { ... }
> >
> > or even better:
> >    const size_t len = strlen(s);
> >    for (size_t i = 0; i < len; ++i) { ... }
> >
> > size_t exists at least since C99 (1999).
>
> Yes, that's the point of the original post. They're asking for a
> warning to tell developers not to do it.
>

Reply via email to