Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a pretty long sqlite query:

const char *sql_query = "SELECT statuses.word_id FROM lang1_words, statuses WHERE statuses.word_id = lang1_words.word_id ORDER BY lang1_words.word ASC"; 

How can I break it in a number of lines to make it easier to read? If I do the following:

const char *sql_query = "SELECT word_id                         FROM table1, table2                         WHERE table2.word_id = table1.word_id                         ORDER BY table1.word ASC"; 

I am getting an error.

Is there a way to write queries in multiple lines?

like image 695
Ilya Suzdalnitski Avatar asked Apr 28 '09 11:04

Ilya Suzdalnitski


People also ask

How do I split a string into multiple lines?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

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

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!

How do you split lines in code?

Use the line-continuation character, which is an underscore ( _ ), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return) or (starting with version 16.0) a comment followed by a carriage return.

What is AC string literal?

A "string literal" is a sequence of characters from the source character set enclosed in double quotation marks (" "). String literals are used to represent a sequence of characters which, taken together, form a null-terminated string.


1 Answers

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" 
like image 66
Georg Schölly Avatar answered Oct 06 '22 18:10

Georg Schölly