Created: 2023-01-10 15:23
Status: #concept
Subject: Programming
Tags: C C Array C String

String Literal

AKA: String Constant, Constant String

A C Array of Characters enclosed in double quotation marks "".

// a single string literal
puts("When you come to a fork in the road, take it.");

// adjacent string literals are concatenated into a single literal 
puts("I am string one" " I am string two\n"
	 "I am string three");

Escape Sequences

When using a combination of a backslash character \ and another specific character, you can "escape" into different characters not usually accessible with the keyboard.

  • an exception of this is the %% character which prints a %.

Escape sequence Character represented
\a Alert (bell, alarm)
\b Backspace
\f Form feed (new page)
\n New line (Enter key)
\r Carriage return
\t Horizontal tab
\v Vertical tab
\' Single quotation mark
\" Double quotation mark
\? Question mark
\\ Backslash
\0 Null Terminator

Operations with String Literals

Since string literals are Constant Character C Arrays, we can use them wherever const char * values are needed.

char *str;
str = "abc"; // pointer address points to the first element of {'a','b','c','\0'}

char ch;
ch = "abc"[1]; // sets ch to 'b'

Common Pitfalls

We cannot edit the individual characters of a String Literal, we have to use a String Variable instead.

char *literal = "I cannot change my letters, only the string I'm pointing to."
char variable[MAX_LEN+1] = "I can index & change my own letters." 

References