[Bug c++/78679] Produce a warning on `int + string literal`

redi at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Tue Aug 29 21:53:00 GMT 2017


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=78679

--- Comment #2 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to Vittorio Romeo from comment #0)
> This code snippet
> 
>     int main()
>     {
>         auto a = 6 + ".txt";   
>     }
> 
> does not produce any warning with `-Wall -Wextra -Wpedantic`.
> 
> I think this is a common beginner mistake that a warning could avoid.

But this is valid C++ code, and there are valid reasons to write that. The fact
it does something different to what a beginner might expect doesn't mean it
should warn. Certainly not with -Wall.

// returns either "long-filename.txt" or "filename.txt"
const char* filename(bool shortname)
{
  return (shortname ? 5 : 0) + "long-filename.txt";
}

I'm curious what the precise behaviour of Clang's -Wstring-plus-int is, and
which cases it does/doesn't warn about. It warns about this case:

prog.cc:4:30: warning: adding 'int' to a string does not append to the string
[-Wstring-plus-int]
  return (shortname ? 5 : 0) + "long-filename.txt";
         ~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~
prog.cc:4:30: note: use array indexing to silence this warning
1 warning generated.

But using array indexing would not improve the code IMHO:

  return &"long-filename.txt"[shortname ? 5 : 0];


More information about the Gcc-bugs mailing list