With the constant chopping and changing back and forth between different languages, every now and then I find myself trying to write fragments of Python or JS syntax in C/C++.
One that's caught me out more than once is trying to append a number to a string literal with a +
operator:
foo(const char*);
foo("the number is " + 6);
Which happily compiles to pass a char*
pointer to the string "mber is "
into my function. Even more fun, if I write:
foo("the number is " + 20);
Is anyone aware of a warning option that can catch this?
GCC does warn about the out-of-bound pointer arithmetic as one would expect, via the -Warray-bounds
warning that is included in -Wall
. However optimizations need to be enabled for this to work, e.g. with the options -Wall -O2
GCC 13 produces:
<source>:4:45: warning: array subscript 20 is outside array bounds of 'const char [15]' [-Warray-bounds=]
4 | some_function_that_takes_a_const_chr_ptr("the number is " + 20);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~
For the in-bounds case Clang has a -Wstring-plus-int
warning, but GCC currently does not have an equivalent.
A patch to implement an equivalent was submitted in 2017, but seems to have never proceeded further.