Jump to: navigation, search

The C Programming Language, 2nd Edition, by Kernighan and Ritchie
Exercise 1.02 on page 8

Experiment to find out what happens when printf 's argument string contains \c, where c is some character not listed above.



Solution by Richard Heathfield

By 'above', the question is referring to:
\n (newline)
\t (tab)
\b (backspace)
\" (double quote)
\\ (backslash)

We have to tread carefully here, because using a non-specified escape sequence invokes undefined behaviour. The following program attempts to demonstrate all the legal escape sequences, not including the ones already shown (except \n , which I actually need in the program), and not including hexadecimal and octal escape sequences.

#include <stdio.h>

int main(void)
{
  printf("Audible or visual alert. \a\n");  
  printf("Form feed. \f\n");
  printf("This escape, \r, moves the active position to the initial position of the current line.\n");
  printf("Vertical tab \v is tricky, as its behaviour is unspecified under certain conditions.\n");

  return 0;
}

Solution by sl4y3r 0wn3r

#include <stdio.h>
int main(void)
{
  printf("alert (0x07) - added in C89: '\a'\n");
  printf("backspace (0x08): ' \b'\n");
  printf("horizontal tab (0x09): '\t'\n");
  printf("newline (0x0A): '\n'\n");
  printf("vertical tab (0x0B):'\v'\n");
  printf("formfeed (0x0C): '\f'\n");
  printf("carriage return (0x0D): '\r'\n");
  printf("double quote: (0x22)'\"'\n");
  printf("single quote (0x27): '\''\n");
  printf("question mark (0x3F): '\?'\n");
  printf("backslash (0x5C): '\\'\n");
  printf("octal number (nnn): '\101'\n");

  /* *
   * ASCII  Hexadecimal
   *   A        41
   * */
  printf("hexdecimal number (xhh): '\x41'\n");
  printf("escape character (0x1B): '\e'\n");

  /* *
   * ASCII  Decimal Octal
   *   A       65    101
   * */
  printf("using format string as escape sequence: %d\n", ('\101'));

  /* *
   * warning: universal character names are only valid in C++ and C99
   * printf("unicode character (UTF-32[hex]: Uhhhhhhhh): '\U00000023'\n");
   * printf("unicode character (UTF-16[hex]: Uhhhh): '\u0023'\n");
   * */

  return 0;

}

Output:

alert (0x07) - added in C89: ''
backspace (0x08): ''
horizontal tab (0x09): '	'
newline (0x0A): '
'
vertical tab (0x0B):'
                     '
formfeed (0x0C): '
                  '
'arriage return (0x0D): '
double quote: (0x22)'"'
single quote (0x27): '''
question mark (0x3F): '?'
backslash (0x5C): '\'
octal number (nnn): 'A'
hexdecimal number (xhh): 'A'
escape character (0x1B): '
using format string as escape sequence: 65

Personal tools