DEV Community

Cover image for ESCAPE SEQUENCES IN C
Bittu Kumar
Bittu Kumar

Posted on

ESCAPE SEQUENCES IN C

#c

Hello everyone, This is my 1st post on dev.to in which I would like to tell you about ESCAPE SEQUENCES IN C...

In C, escape sequences are special character sequences that represent characters which cannot be easily typed or are non-printable. Here’s a brief overview of some common escape sequences and an example demonstrating their usage:-

LIST OF COMMON ESCAPE SEQUENCES IN C

. \\ - Backslash

Represents a literal backslash.
Example: printf("This is a backslash: \\");
// Output: This ia a backslash: \

. \n - Newline

Moves the cursor to the next line.
Example: printf("Hello\nWorld");
// Output:
Hello
World

. \t - Horizontal Tab

Moves the cursor to the next tab stop.
Example: printf("Name \tAge\nAlice \t30");
// Output:
Name Age
Alice 30

. \r - Carriage Return

Moves the cursor to the beginning of the current line.
Example: printf("12345\rAB");
// Output: AB345

. \a - Alert (Bell)

Example: printf("Warning!\a");
Output : Produces an audible bell sound (might not be heard on all systems).

. \0 - Null Character
Marks the end of a string in C.
Example: char str[] = "Hello\0World";
Output : // Only "Hello" is printed.

Example Code - Here’s a concise example showing some of these escape sequences in action:-

int main() {
printf("This is a backslash: \ \n");
printf("This is on a new line.\n");
printf("Here is a tab:\tTabbed text.\n");
printf("Carriage return:\rOverwritten\n");
printf("Alert sound:\a\n");
printf("Null character example: Hello\0World\n")
return 0;
}

Explanation of Output

  • \: Outputs a single backslash.
  • \n: Moves to the next line.
  • \t: Inserts a tab space.
  • \r: Overwrites the beginning of the current line with new text.
  • \a: Triggers an alert sound (if supported).
  • \0: Ends the string at "Hello", so "World" is not printed.

Escape sequences are essential for formatting output and including special characters in strings in C programming.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas
  • You really should learn how to use Markdown to format code examples properly.
  • Your first null character example is wrong: it produces no output because the code never actually calls printf().
  • The behavior of \a is terminal-dependent. Some terminal settings make the bell visual instead of audible.
  • The behavior of \r is both stream- and terminal-dependent.
  • \t is not a "tab space"; it's just a "tab."
  • Embedding \0 within strings makes the remainder of the string effectively "dead" except in very special circumstances, so you generally shouldn't do it. Typically, \0 is shown in examples either to explicitly test for \0 as a character or assign to the end of a string.
  • This information is covered in many, many places already.
Collapse
 
imabhinavdev profile image
Abhinav Singh

Great👏