Escape Sequences in C | Complete Guide with Examples

Escape Sequences in C | Complete Guide with Examples

Escape Sequences in C | Complete Guide with Examples

Introduction

Escape sequences in C are special character combinations used to represent characters that are difficult or impossible to type directly in a string. They are typically used in formatting output, representing special characters, and controlling text display.


What Are Escape Sequences?

  • An escape sequence starts with a backslash (\) followed by a specific character.
  • They are interpreted differently by the compiler to perform special tasks like adding a newline, inserting a tab, or printing quotes.

Commonly Used Escape Sequences in C

Escape SequenceDescriptionExample Output
\nNewline (Moves cursor to next line)"Hello\nWorld" → Hello (new line) World
\tHorizontal Tab (Adds tab space)"A\tB" → A B
\\Backslash (Prints \)"C:\\Program Files" → C:\Program Files
\'Single Quote'\'A\'' → ‘A’
\"Double Quote"He said \"Hello\"" → He said “Hello”
\rCarriage Return (Moves cursor to start of line)"Hello\rHi"Hilo
\bBackspace (Deletes previous character)"AB\bC"AC
\fForm Feed (Page break)Rarely used
\vVertical TabRarely used
\0Null Character (Indicates string termination)Used to end strings

Examples of Escape Sequences in Action

1. Using \n (Newline) and \t (Tab)

#include <stdio.h>

int main() {
printf("Hello\nWorld!\n");
printf("Name:\tJohn\nAge:\t25\n");
return 0;
}

Output:

Hello
World!
Name: John
Age: 25

2. Using \\, \', and \"

#include <stdio.h>

int main() {
printf("C:\\Program Files\\MyApp\n");
printf("He said, \"Hello!\"\n");
printf("It\'s a great day!\n");
return 0;
}

Output:

C:\Program Files\MyApp
He said, "Hello!"
It's a great day!

3. Using \b (Backspace) and \r (Carriage Return)

cCopyEdit#include <stdio.h>

int main() {
    printf("Hello\b World!\n");  // Backspace removes 'o'
    printf("Start\rEnd\n");       // Moves cursor to the beginning
    return 0;
}

Output:

Hell World!
End

4. Using \0 (Null Character) in Strings

#include <stdio.h>

int main() {
char str[] = "Hello\0World!";
printf("%s\n", str); // Only prints "Hello"
return 0;
}

Output:

Hello

Conclusion

Escape sequences in C enhance text formatting and allow special characters to be used in strings. Mastering them will help you write cleaner and more readable C programs.

Escape Sequences in C | Complete Guide with Examples