escape-sequence

“Everything you need comes to you in perfect time, space and sequence” Louise Hay

There are some types of character that don’t have a written symbol and are basically non-printable.

Some of these characters are:

  • White-space: Tab, backspace, newline, space.

  • Computer alarm.

  • Form feed

Also because we use single quotations when want to assign characters to a variable typed char. We can’t use the single quotation itself as the value to be stored in a char-variable.

For example:

//WRONG
char character = ''';

When a compiler tries to compile this statement, it will get confuse about where the first and last single quotation mark is! And so it will stop compiling and return error instead.

But C++ brought an alternative to these characters called escape-sequence which allow us to use these non-printable characters and add single and double quotation mark to char-variables in a program.

The effect of using these escape-sequence is exactly the same as if we’re using those especial characters.

Sequence Meaning
a Alert (ANSI C)
b Backspace
f Form feed
n Newline
r Carriage return
t Horizontal tab
v Vertical tab
\ Backslash ()
Single quote (‘)
Double quote (“)
? Question mark (?)
oo Octal value. (o represents an octal digit)
xhh Hexadecimal value. (h represents a hexadecimal digit.)

Example:


char character = ''';

Now because we used the escape-sequence single-quotation mark, the character variable can store the single-quotation mark and the compiler will not complain about this statement any more.

Another example:

#include <iostream>
using namespace std
int
main() {

cout<<"You'll here 3 beeps now: a a a nThis message is printing on a new line. ";
return 0;
}

Output: If you compile and run the example above, you’ll hear 3 beep alarms from your computer because we used a 3 times.