String literals
- C course
- Beginner
- Lesson 60/116
- 4 min
Learn string literals with double quotes and escape sequences.
Creating strings with string literals
Text inside double quotes is a string literal. C automatically appends '\0'; you do not write it yourself.
char city[] = "Paris";
/* city: {'P','a','r','i','s','\0'} */The array size is computed automatically: 5 letters + 1 null = 6 elements. Using a string literal is shorter and clearer than listing characters one by one.
Computing array size
Leaving the array size empty ([]) when assigning a string literal lets C compute it for you. But if you give the size by hand, you must add one for the null character.
char s1[] = "Hello"; /* 6 elements: 5 letters + 1 null */
char s2[6] = "Hello"; /* same: 5+1 */If you write char s2[5] = "Hello"; there is no room for the null character, which is undefined behavior. sizeof(s1) returns the full array size; this is one more than the letter count.
Practice Define a city string and print it
Initialize a char array with the string literal "Paris". Print its size in bytes with sizeof; then print the string with printf %s. Output is size first, then string.
Starter code
#include <stdio.h>
int main(void) {
/* initialize char array with "Paris" literal */
/* print byte size with sizeof */
/* print string with printf %s */
return 0;
}Sample solution
#include <stdio.h>
int main(void) {
char city[] = "Paris";
printf("%zu\n", sizeof(city));
printf("%s\n", city);
return 0;
}Expected output
6 Paris
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 String literal assignment
char fruit[] = ____; /* "Apple" string */
char fruit[] = "Apple"; /* "Apple" string */
Explanation: "Apple" is a string literal in double quotes.
2 Which of the following is a valid string literal?
- "Hello" Correct answer
- `Hello`
- {Hello}
- 'Hello'
Explanation: "Hello" is a string literal in double quotes.
3 Match string definitions
| Term | Meaning |
|---|---|
"Ali" |
string literal |
char |
character type |
\0 |
auto appended |
sizeof |
byte size of array |