What is the purpose of escape characters in the C language?
The purpose of escape characters is to represent special or control characters within a string. In C language, escape characters are represented by using a backslash (\) before the character or string.
Common escape characters include:
- \n: line break marker
- Tab: Tabulation character
- Carriage return: Enter key
- ‘
or
‘ : single quotation mark
- quotation mark
- backslash
By using escape characters, we are able to insert special characters or control characters into a string without causing errors in the compiler. For example, using \n can create a new line in the output instead of interpreting it as the end of the string. Similarly, using \t can create a tab in the output, allowing for alignment.
Here is an example of using escape characters:
#include <stdio.h>
int main() {
printf("Hello\tWorld!\n");
printf("This is a new line.\n");
printf("He said, \"Hello!\"\n");
printf("This is a backslash: \\");
return 0;
}
Output:
Hello World!
This is a new line.
He said, "Hello!"
This is a backslash: \