Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 536
deft_code Avatar asked Mar 24 '10 00:03

deft_code


People also ask

What is the purpose of string concatenation?

The concatenation operators combine two strings to form one string by appending the second string to the right-hand end of the first string.

What is the purpose of concatenation operator?

Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & . Both carry out the basic concatenation operation, as the following example shows.

What is the purpose of concatenation Python?

Concatenating means obtaining a new string that contains both of the original strings. In Python, there are a few ways to concatenate or combine strings. The new string that is created is referred to as a string object. In order to merge two strings into a single object, you may use the + operator.

Can you concatenate to a string literal?

String literalsThe code concatenates the smaller strings to create the long string literal. The parts are concatenated into a single string at compile time.


1 Answers

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
like image 147
Carl Norum Avatar answered Sep 30 '22 20:09

Carl Norum