Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does concatenation of two string literals work?

Tags:

c

string

char* a="dsa" "qwe"; printf("%s", a); 

output: dsaqwe

My question is why does this thing work. If I give a space or nothing in between two string literals it concatenates the string literals.

How is this working?

like image 340
grv Avatar asked Aug 25 '12 09:08

grv


People also ask

How do you concatenate string literals?

Concatenate string literals in C/C++ A string literal is a sequence of characters, enclosed in double quotation marks (" ") , which is used to represent a null-terminated string in C/C++. If we try to concatenate two string literals using the + operator, it will fail.

How does string concatenation work internally?

String concatenation using StringBuilder class It is mutable class which means values stored in StringBuilder objects can be updated or changed. In the above code snippet, s1, s2 and s are declared as objects of StringBuilder class. s stores the result of concatenation of s1 and s2 using append() method.

How does concatenation operator work?

The concatenation operator is a binary operator, whose syntax is shown in the general diagram for an SQL Expression. You can use the concatenation operator ( || ) to concatenate two expressions that evaluate to character data types or to numeric data types.

How does string concatenation work C++?

C++ has a built-in method to concatenate strings. The strcat() method is used to concatenate strings in C++. The strcat() function takes char array as input and then concatenates the input values passed to the function. In the above example, we have declared two char arrays mainly str1 and str2 of size 100 characters.


1 Answers

It's defined by the ISO C standard, adjacent string literals are combined into a single one.

The language is a little dry (it is a standard after all) but section 6.4.5 String literals of C11 states:

In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed wide string literal tokens are concatenated into a single multibyte character sequence.

This is also mentioned in 5.1.1.2 Translation phases, point 6 of the same standard, though a little more succinctly:

Adjacent string literal tokens are concatenated.

This basically means that "abc" "def" is no different to "abcdef".

It's often useful for making long strings while still having nice formatting, something like:

const char *myString = "This is a really long "                        "string and I don't want "                        "to make my lines in the "                        "editor too long, because "                        "I'm basically anal retentive :-)"; 
like image 116
paxdiablo Avatar answered Oct 27 '22 00:10

paxdiablo