Escape Sequences in C

Escape Sequences in C

Understanding Escape Sequences in C with Examples

In C programming, escape sequences are used within string literals to represent characters that are either difficult to type or have special meanings. They start with a backslash (\) followed by a specific character or set of characters.

Example Program

#include <stdio.h>

int main() {
    // Using different escape sequences in C

    // Newline escape sequence
    printf("Hello, World!\\n");

    // Tab escape sequence
    printf("Column1\\tColumn2\\tColumn3\\n");

    // Backslash escape sequence
    printf("This is a backslash: \\\\n");

    // Double quote escape sequence
    printf("She said, \\"Hello!\\"\\n");

    // Single quote escape sequence
    printf("This is a single quote: \\'\\n");

    // Carriage return escape sequence
    printf("This will overwrite the previous text.\\rNew text\\n");

    return 0;
}

Explanation of Escape Sequences

  • Newline (\n): Moves the cursor to the next line.
    Hello, World!
  • Tab (\t): Inserts a horizontal tab space.
    Column1 Column2 Column3
  • Backslash (\\): Inserts a backslash character.
    This is a backslash: \
  • Double Quote (\"): Inserts a double quote character within a string.
    She said, "Hello!"
  • Single Quote (\'): Inserts a single quote character within a string.
    This is a single quote: '
  • Carriage Return (\r): Moves the cursor to the beginning of the line, overwriting text.
    New text

Each escape sequence serves a specific purpose, making it easier to format text and include special characters in your output.

Comments

Popular Posts