String Literals in C
A string literal in C is a sequence of characters enclosed within double quotes (" "). It represents a
constant sequence of characters in the source code and is used to initialize string variables or
directly as arguments to functions.
In C programming, string literals are not just sequences of characters, but they also come with a
special memory representation due to the null-terminator (\0) that indicates the end of the string.
String literals are widely used in C programs for handling text, printing outputs, and initializing
variables.
Syntax for String Literals
A string literal is written as a sequence of characters enclosed by double quotes. For example:
"Hello, World!" is a string literal in C.
String literals are automatically terminated with the null character '\0'. This null character is essential
for the correct handling of strings in C.
For example, the string literal "Hello" is represented internally as: {'H', 'e', 'l', 'l', 'o', '\0'}
Key Characteristics of String Literals in C
1. **Immutability**: String literals are immutable, meaning they cannot be modified directly once
declared.
2. **Null Terminator (`\0`)**: Every string literal in C is automatically null-terminated, which marks the
end of the string.
3. **Memory Allocation**: String literals are stored in read-only sections of memory, which prevents
modification during runtime.
4. **Size**: The size of a string literal is the number of characters plus one for the null terminator
(e.g., "Hello" has a size of 6, with the null terminator included).
Example of String Literals in C
#include <stdio.h>
int main() {
// Declare a string literal
char greeting[] = "Hello, World!";
// Print the string literal
printf("%s\n", greeting);
// Print the length of the string (excluding null terminator)
printf("Length of the string: %zu\n", strlen(greeting));
return 0;
Explanation of the Example
In this example, the string literal "Hello, World!" is stored in the `greeting[]` array, and the null
terminator `\0` is automatically added to mark the end of the string.
The `strlen()` function calculates the length of the string excluding the null terminator, which in this
case is 13.
Invalid Modification of String Literals
In C, trying to modify a string literal directly results in undefined behavior. String literals are typically
stored in read-only memory.
Example:
char *str = "Hello, World!";
str[0] = 'J'; // Undefined behavior: string literals are immutable
This will lead to a segmentation fault or some other runtime error.
Conclusion
String literals in C are a fundamental feature for representing text. They are automatically
null-terminated and stored in memory in a read-only section to prevent modification during runtime.
Since they are immutable, string literals should not be modified directly, and this behavior ensures
program stability and consistency.