Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ warn or prohibit literal string concatenation

Is there a way to warn or prohibit literal string concatenations such as:

const char *a = "foo" " bar";

I spent hours finding a bug in a big static array that had

const char * a[] = {"foo" "bar"};

instead of

const char * a[] = {"foo", "bar"};
like image 272
gozag Avatar asked Sep 05 '25 15:09

gozag


1 Answers

Clang has a warning -Wstring-concatenation that is explicitly designed to catch such bugs:

warning: suspicious concatenation of string literals in an array initialization; did you mean to separate the elements with a comma? [-Wstring-concatenation]
char const *a[]  = { "ok", "foo" "bar", "ok"};
                                 ^
                                ,

This won't exactly work for the toy example you showed because you need to have several initializers and only miss commas in a couple of places, i.e.:

// no warning
char const *b[]  = {"foo" "bar"};
// no warning
char const *c[]  = {"ok", "foo" "bar"};
// no warning
char const *d[]  = {"foo" "bar", "ok"};

But when you have a large number of initializers in an array and only make a typo in a couple of places, this seems ideal.

Here's a demo.

GCC doesn't appear to have an equivalent warning, but there is a request for it to be added.

Note that this only works for array initialization. Your example of

const char *x = "foo" " bar";

won't be detected by this warning (or any other that I'm aware of).

Also note that enabling this warning may yield a lot of false positives, but you can use it sparingly when trying to catch bugs.

like image 138
cigien Avatar answered Sep 08 '25 17:09

cigien