Tuesday, April 3, 2012

Escape Sequences in C Programming Language

Let’s have a look at a simple C program:


#include
main ( )
{
printf ("This is easy !!\n");
}


You might be wondering about the \n (pronounced backslash n) in the string argument of the function printf ( ):

"This is easy!!\n"

The \n is an example of an escape sequence: it's used to print the newline character. If You have executed Programs 1.1 or 1.2 you will have noticed that the \n doesn't appear in the output Each \n in the string argument of a printf ()causes the cursor to be placed at the beginning of die next line of output. Think of an escape sequence as a "substitute character" for printing hard-to-get characters. In an earlier section we learnt that s are not allowed in strings., but including \n's within one makes it easy to output it in several lines: if you wish to print a string in two or more lines, place the \n wherever you want to insert a new line in the output, as in the example below:

main ( )
{
printf ("This\nstring\nwill\nbe\nprinted\,nin\n9\nlines.\n");
}

Each \n will force the cursor to be positioned at the beginning of the next line on the screen, from where further printing will begin. Here is part of the output from executing the above program:

This
string
will
etc.

If a string does not contain a \n at its end, the next string to be printed will begin in the same line as the last, at the current position of the cursor, i.e. alongside the first string.

We have seen that the "double quotes" character is used to mark the beginning and end of a C string. How then can the "double quotes" character itself be included within a string? This time the escape sequence \" comes to our aid: it prints as “ in the output. Similarly, the escape sequence, \\ helps print \, and \' the single quote character,'. All escape sequences in C begin with a backslash.

Be careful to remember that "" is not the escape sequence for the "double quote" character (as it is in some versions of BASIC). In C "" is the null string., the null string is not "empty ", as one might have thought; it contains a single character, the null character, ASCII 0 (in which all bits are set to zero). We will see later that the last character of every C string is the (invisible) null character. Its presence helps the computer determine the actual end of the string.

Other escape sequences available in C are:

\a

ring terminal bell (the a is for alert) [ANSI] extension]

\?

question mark [ANSI extension]

\b

Backspace

\r

carriage return

\f

Formfeed

\t

horizontal tab

\V

vertical tab

\O

ASCII null character

Placing any of these within a string causes either the indicated action, or the related character to be output.

0 comments:

Post a Comment