Cloudbook: C

  1. Home
  2. Variables
  3. Strings
  4. § 2 exercise →
Strings

To keep things simple, our strings will contain characters from the set of plain text characters, some printing, and some (like \n) non-printing. To get a string value into the program, the string needs a representation. This representation is called a string literal.

Mostly, the string looks like itself - the string value "Hello world!" is represented by the literal "Hello world!". However, the double quotes which are required to create the string literal are not part of the string value. In fact, a string literal is basically a bunch of characters between a pair of single or double quotes.

Complications arise when you want a pair of double quotes to be part of the string, as in "I said, "Hello World!"". The computer is not smart enough to understand that the quotes tightly around "Hello World!" are just plain text characters, and not program elements that begin and end strings.

There are two solutions. Either write it like this: 'I said, "Hello World!"'; or like this: "I said \"Hello World!\"".

The rule that is being invoked in the first solution is that inside a string literal defined by a pair of single quotes, double quotes are just plain characters. Conversely, inside a string literal defined by a pair of double quotes, single quotes are just plain characters. This is useful so that you can write "Hello Perl's World!" just like that.

The rule that is being invoked in the second solution is that the backslash makes the next character non-special, if it is special. (If the next character is non-special, like n, it might make it special, as in \n.). Since \ is special, it makes itself non-special in the sequence \\.