String Literal


String literals in C++ are all the strings enclosed in double quotation marks, "text" for example. They're arrays of bytes, of type char, with an extra char at the end to indicate termination, which is '\0'1. Remember that they're not just placeholders, meaning they actually have an address at which the literal string is maintained. Their type is const char*.

A common beginner error when dealing with string literals is to think that the following two statements are equivalent:

char myName[] = "GReaperEx";
char *myName = "GReaperEx";

Although they may look similar, what happens under the hood is different. In particular, while the first copies the string literal unto a new location, the second just copies the address2. This shouldn't be an issue, but don't forget that a string literal is of type const char*, and to make things even more complicated, almost all compilers load those strings to read-only memory. As a result, if you try to change the contents of any string literal, the program will compile without complaints, but when run it will crash3.

A way to avoid that situation, we can declare myName as const char*, to make the compiler throw errors when you try to change its contents.

Compiler behavior

Any strings adjacent to each other will be joined together, for example "My" " little " "pony." would become "My little pony.".

A string normally can't continue for more than a single line, but if you put the escape character( \ ) and immediately after that hit enter, it will carry to the next line. That escape character and the enter are ignored though.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution 3.0 License