How to split a string literal across multiple lines in C / Objective-C?

There are two ways to split strings over multiple lines:

  1. Each string on its own line. Works only with strings:

    • Plain C:

      char *my_string = "Line 1 "
                        "Line 2";
      
    • Objective-C:

      NSString *my_string = @"Line1 "
                             "Line2";    // the second @ is optional
      
  2. Using \ – can be used for any expression:

    • Plain C:

      char *my_string = "Line 1 \
                         Line 2";
      
    • Objective-C:

      NSString *my_string = @"Line1 \
                              Line2";
      

The first approach is better, because there isn’t a lot of whitespace included. For a SQL query however, both are possible.

NOTE: With a #define, you have to add an extra \ to concatenate the two strings:

Plain C:

#define kMyString "Line 1"\
                  "Line 2"

Leave a Comment