This post will discuss how to 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. For instance, consider the following code, which results in a compilation error:

C


Download Code

Compilation Error:

error: invalid operands to binary + (have ‘char *’ and ‘char *’)
char* s = "concatenate" + " string literals ";
~~~~~~~~~~~~~ ^

C++


Download Code

Compilation Error:

error: invalid operands of types ‘const char [12]’ and ‘const char [18]’ to binary ‘operator+’
std::string s = "concatenate" + " string literals ";
~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~

 
This is because string literals have a pointer type, char * (C) or const char [n] (C++), which cannot be added using the + operator. Also, they don’t get automatically converted to C++’s std::string.

1. Implicit concatenation

C/C++ provides implicit string literal concatenation, where adjacent string literals are joined into a single literal during compile time. This implicit concatenation is often used to satisfy C/C++’s syntactic requirements and split string literals across multiple lines without the need for a line continuation character.

C


Download  Run Code

Output:

Concatenate string literals in C

C++


Download  Run Code

Output:

Concatenate string literals to std::string

2. C++ – Using string constructor

As seen above, the operator + does not work with the pointer type, but the + operator is overloaded for std::string and can concatenate two string objects. To use string literals with std::string, we need to convert them to a string object first. This can be easily done using a string constructor, as shown below:

Download  Run Code

Output:

Concatenate string literals to std::string

That’s all about concatenating string literals in C/C++.