Character Strings in C: More on Constant Strings

If you place a backslash character at the very end of the line and follow it immediately by a carriage return, it tells the C compiler to ignore the end of the line. This line con- tinuation technique is used primarily for continuing long constant character strings onto the next line and, as you see in Chapter 13, “The Preprocessor,” for continuing a macro definition onto the next line.

Without the line continuation character, your C compiler generates an error message if you attempt to initialize a character string across multiple lines; for example:

char letters[] =

{ “abcdefghijklmnopqrstuvwxyz

ABCDEFGHIJKLMNOPQRSTUVWXYZ” };

By placing a backslash character at the end of each line to be continued, a character string constant can be written over multiple lines:

char letters[] =

{ “abcdefghijklmnopqrstuvwxyz\

ABCDEFGHIJKLMNOPQRSTUVWXYZ” };

It is necessary to begin the continuation of the character string constant at the beginning of the next line because, otherwise, the leading blank spaces on the line get stored in the character string. The preceding statement, therefore, has the net result of defining the character array letters and of initializing its elements to the character string

“abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”

Another way to break up long character strings is to divide them into two or more adja- cent strings. Adjacent strings are constant strings separated by zero or more spaces, tabs, or newlines. The compiler automatically concatenates adjacent strings together. Therefore, writing the strings

“one” “two” “three”

is syntactically equivalent to writing the single string

“onetwothree”

So, the letters array can also be set to the letters of the alphabet by writing

char letters[] =

{ “abcdefghijklmnopqrstuvwxyz” “ABCDEFGHIJKLMNOPQRSTUVWXYZ” };

Finally, the three printf calls

printf (“Programming in C is fun\n”);

printf (“Programming”  ” in C is fun\n”);

printf (“Programming”  ” in C” ” is fun\n”);

all pass a single argument to printf because the compiler concatenates the strings together in the second and third calls.

Source: Kochan Stephen G. (2004), Programming in C: A Complete Introduction to the C Programming Language, Sams; Subsequent edition.

Leave a Reply

Your email address will not be published. Required fields are marked *