public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Question about -Wstrict-overflow=2
@ 2021-03-06 10:37 Alexander Motzkau
  2021-03-06 11:23 ` Andrew Haley
  0 siblings, 1 reply; 11+ messages in thread
From: Alexander Motzkau @ 2021-03-06 10:37 UTC (permalink / raw)
  To: gcc-help

Hi everyone,

I have a question how to fix a -Wstrict-overflow=2 warning. Please consider
this (very) simplified example:

    #include <stdbool.h>
    #include <stddef.h>

    char* get_buf();
    bool do_round();

    bool fun()
    {
        char *expbuf = get_buf();
        char *argptr = expbuf;
        char *endbuf = expbuf + 120;

        while(true)
        {
            if (argptr >= endbuf)
                return false;

            if (!do_round())
                break;

            argptr++;
        }

        return true;
    }

gcc -O2 -Wstrict-overflow=2 gives a warning 'assuming pointer wraparound
does not occur when comparing P +- C1 with P +- C2 [-Wstrict-overflow]' for
the first if condition in GCC 9 as well as GCC 10. Although the wording of
the warning is questionable - the compiler may always assume I write
standard conforming code without telling me about it - the documentation
says this warning comes when a comparison is simplified to a constant.
A constant result would mean that the if block always or never happens
which would be quite undesirable.

Looking at the assembly output with Matt Godbolt's Compiler Explorer however
it seems that there's nothing wrong. GCC modified the loop to use an index
variable counting from 120 backwards. Clever, but clearly not a constant to
warn about.

So the question is what this warning is really about and how to get rid of
it?

If I change the condition to 'argptr - endbuf >= 0' the warning goes away,
but so does the optimization. The resulting code then has a worse
performance and worse readability.

Is there indeed something wrong with the code that I didn't see?
Or is there anything I can do to silence the warning apart from going to
-Wstrict-overflow=1?

Thanks,
Alex

^ permalink raw reply	[flat|nested] 11+ messages in thread

end of thread, other threads:[~2021-03-09  9:09 UTC | newest]

Thread overview: 11+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2021-03-06 10:37 Question about -Wstrict-overflow=2 Alexander Motzkau
2021-03-06 11:23 ` Andrew Haley
2021-03-06 12:03   ` Alexander Motzkau
2021-03-07 11:37     ` Andrew Haley
2021-03-07 14:04       ` Alexander Motzkau
2021-03-07 14:56         ` Andrew Haley
2021-03-08 16:43           ` Segher Boessenkool
2021-03-07 15:31         ` Ian Lance Taylor
2021-03-08 21:05         ` Martin Sebor
2021-03-08 21:57           ` Alexander Motzkau
2021-03-09  9:09           ` Andrew Haley

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).