Why allow concatenation of string literals?

I was recently bitten by a subtle bug.

char ** int2str = {
   "zero", // 0
   "one",  // 1
   "two"   // 2
   "three",// 3
   nullptr };

assert( int2str[1] == std::string("one") ); // passes
assert( int2str[2] == std::string("two") ); // fails

If you have godlike code review powers you'll notice I forgot the , after "two".

After the considerable effort to find that bug I've got to ask why would anyone ever want this behavior?

I can see how this might be useful for macro magic, but then why is this a "feature" in a modern language like python?

Have you ever used string literal concatenation in production code?


Solution 1:

Sure, it's the easy way to make your code look good:

char *someGlobalString = "very long "
                         "so broken "
                         "onto multiple "
                         "lines";

The best reason, though, is for weird printf formats, like type forcing:

uint64_t num = 5;
printf("Here is a number:  %"PRIX64", what do you think of that?", num);

There are a bunch of those defined, and they can come in handy if you have type size requirements. Check them all out at this link. A few examples:

PRIo8 PRIoLEAST16 PRIoFAST32 PRIoMAX PRIoPTR

Solution 2:

It's a great feature that allows you to combine preprocessor strings with your strings.

// Here we define the correct printf modifier for time_t
#ifdef TIME_T_LONG
    #define TIME_T_MOD "l"
#elif defined(TIME_T_LONG_LONG)
    #define TIME_T_MOD "ll"
#else
    #define TIME_T_MOD ""
#endif

// And he we merge the modifier into the rest of our format string
printf("time is %" TIME_T_MOD "u\n", time(0));