Concatenate string literals in C/C++
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
1 2 3 4 5 6 7 8 9 |
#include <stdio.h> int main(void) { char* s = "concatenate" + " string literals "; printf("%s", s); return 0; } |
Compilation Error:
error: invalid operands to binary + (have ‘char *’ and ‘char *’)
char* s = "concatenate" + " string literals ";
~~~~~~~~~~~~~ ^
C++
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> #include <string> int main() { std::string s = "concatenate" + " string literals "; std::cout << s << std::endl; return 0; } |
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
1 2 3 4 5 6 7 8 9 10 |
#include <stdio.h> int main(void) { char *s = "Concatenate" " string literals " "in C"; printf("%s", s); return 0; } |
Output:
Concatenate string literals in C
C++
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <string> int main() { std::string s = std::string("Concatenate") + std::string(" string literals ") + std::string("to std::string"); std::cout << s << std::endl; return 0; } |
Output:
Concatenate string literals to std::string
That’s all about concatenating string literals in C/C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)