Programming Error – Unintended String Concatenation

In an effort to be helpful, C and C++ compilers concatenate adjacent strings together.

In the following example, the compiler will concatenate the two strings into a single string:

printf("This is a string " "and this is another string.");

Which is probably what you intended anyway.

Because C and C++ are free form languages, adjacent strings can appear in many different formats – as this string table shows:

char *array[] = {
    "str_1",
    "str_2",
    "str_3"
    "str_4",
    "str_5",
    NULL};

Did you notice the missing comma (,) after "str_3"? It can be a hard one to spot.

This is the type of bug that can result in something like a simple parser failing:

if (strcmp(array[i], test_string) == 0)

because str_3 and str_4 will never be matched, but the others will.

Leave a Reply

Your email address will not be published. Required fields are marked *