How do I write a multi-line string literal in C?

What ways do we have to define large string literals in C? Let’s take this example:

#include <stdio.h>
char* my_str = "Here is the first line.\nHere is the second line.";
int main(void) {
  printf("%s\n", my_str);
  return 0;
}

We could first try to split this up as:

char* my_str = "Here is the first line.
Here is the second line.";

This causes a parse error, because literal newline characters are not allowed within the quote.

We can use string literal concatenation. Multiple string literals in a row are joined together:

char* my_str =
  "Here is the first line."
  "Here is the second line.";

But wait! This doesn’t include the newline character; we still have to include it:

char* my_str =
  "Here is the first line.\n"
  "Here is the second line.";

We can also use the backslash character at the end of a line:

char* my_str = "Here is the first line.\
Here is the second line.";

This also doesn’t include the newline! We have to include again:

char* my_str = "Here is the first line.\n\
Here is the second line.";

Apparently in C++11 and in GCC with extensions, we can write “raw strings” like this:

char* my_str = R"Here is the first line.
Here is the second line.";

However, clang doesn’t seem to like this.

The “concatenated string literals” approach has the added advantage of being able to indent the string in your code. I’d use that.

I just released Vidrio, a free app for macOS and Windows to make your screen-sharing awesomely holographic. Vidrio shows your webcam video on your screen, just like a mirror. Then you just share or record your screen with Zoom, QuickTime, or any other app. Vidrio makes your presentations effortlessly engaging, showing your gestures, gazes, and expressions. #1 on Product Hunt. Available for macOS and Windows.

With Vidrio

With generic competitor

More by Jim

Tagged . All content copyright James Fisher 2016. This post is not associated with my employer. Found an error? Edit this page.