C String Literals

In C, a string literal is a sequence of characters enclosed within double quotes (" "). String literals represent constant strings, and they are automatically null-terminated with a null character ('\0') by the C compiler. String literals are used to define and initialize strings in your C programs.

Creating String Literals

You can create string literals by enclosing a sequence of characters within double quotes. For example:

"Hello, World!"

In this case, "Hello, World!" is a string literal representing the string "Hello, World!".

Null Termination

C automatically appends a null character ('\0') to the end of every string literal. This null character marks the end of the string and is used by C to determine the string's length.

Using String Literals to Initialize Variables

String literals can be used to initialize character arrays. For example:

char greeting[] = "Hello!";

In this example, greeting is an array of characters that is initialized with the string literal "Hello!". The size of the character array is determined automatically based on the length of the string literal.

String Literal Constants

String literals are constant and cannot be modified. Attempting to modify the characters in a string literal directly will result in undefined behavior. If you need a mutable string, it's better to use a character array instead.

Concatenation

You can concatenate string literals by placing them next to each other. For example:

"Hello, " "World!"

The C compiler will treat these adjacent string literals as a single string literal.

Escape Sequences

String literals can include escape sequences to represent special characters, such as "\n" for a newline and "\t" for a tab.

"Line 1\nLine 2\tTabbed"

This represents a string with a newline and a tab character.

String literals are fundamental for working with textual data in C. They are often used for initializing strings, displaying messages, and representing constant values in C programs. However, remember that string literals are read-only, and if you need to modify a string, you should use character arrays.