Topic : Programming In C
Author : Brian Kernighan
Page : << Previous 2  Next >>
Go to page :


printf is a more  complicated  function  for  producing
formatted  output.  We will talk about only the simplest use
of it.  Basically, printf uses its first argument as format-
ting  information, and any successive arguments as variables
to be output.  Thus

     printf ("hello, world\n");

is the simplest use  _  the  string  ``hello,  world\n''  is
printed  out.   No  formatting information, no variables, so
the string is dumped out verbatim.  The newline is necessary
to put this out on a line by itself.  (The construction

     "hello, world\n"

is really an array of chars.  More about this shortly.)

     More complicated, if sum is 6,

     printf ("sum is %d\n", sum);

prints

     sum is 6

Within the first argument of printf, the  characters  ``%d''
signify that the next argument in the argument list is to be
printed as a base 10 number.

     Other useful formatting commands are  ``%c''  to  print
out  a  single  character,  ``%s''  to  print  out an entire
string, and ``%o'' to print a number  as  octal  instead  of
decimal (no leading zero).  For example,

     n = 511;
     printf ("What is the value of %d in octal?", n);
     printf ("  %s! %d decimal is %o octal\n", "Right", n, n);


prints

     What is the value of 511 in octal?  Right! 511  decimal
     is 777 octal

Notice that there is no newline at the end of the first out-
put  line.   Successive calls to printf (and/or putchar, for
that matter) simply put out  characters.   No  newlines  are
printed unless you ask for them.  Similarly, on input, char-
acters are read one at a time as you  ask  for  them.   Each
line is generally terminated by a newline (\n), but there is
otherwise no concept of record.

6. If; relational operators; compound statements


     The basic conditional-testing statement in C is the  if
statement:

     c = getchar( );
     if( c == '?' )
             printf("why did you type a question mark?\n");


The simplest form of if is

     if (expression) statement


     The condition to be tested is any  expression  enclosed
in parentheses.  It is followed by a statement.  The expres-
sion is evaluated, and if its value is non-zero, the  state-
ment  is  executed.   There's an optional else clause, to be
described soon.

     The character sequence `=='  is one of  the  relational
operators in C; here is the complete set:

     ==      equal to (.EQ. to Fortraners)
     !=      not equal to
     >       greater than
     <       less than
     >=      greater than or equal to
     <=      less than or equal to


     The value of ``expression relation expression'' is 1 if
the relation is true, and 0 if false.  Don't forget that the
equality test is `=='; a single `='  causes  an  assignment,
not a test, and invariably leads to disaster.

     Tests can be combined with the  operators  `&&'  (AND),
`||'  (OR), and `!' (NOT).  For example, we can test whether
a character is blank or tab or newline with

     if( c==' ' || c=='\t' || c=='\n' ) ...

C guarantees that `&&' and `||' are evaluated left to  right
_ we shall soon see cases where this matters.

     One of the nice things about C is  that  the  statement
part of an if can be made arbitrarily complicated by enclos-
ing a set of statements in {}.  As a simple example, suppose
we want to ensure that a is bigger than b, as part of a sort
routine.  The interchange of a and b takes three  statements
in C, grouped together by {}:

     if (a < b) {
             t = a;
             a = b;
             b = t;
     }



     As a general rule in C, anywhere you can use  a  simple
statement, you can use any compound statement, which is just
a number of simple or compound ones enclosed in  {}.   There
is  no  semicolon  after  the } of a compound statement, but
there _i_s a semicolon after the last  non-compound  statement
inside the {}.

     The ability to replace  single  statements  by  complex
ones  at will is one feature that makes C much more pleasant
to use than Fortran.  Logic (like the exchange in the previ-
ous  example)  which would require several GOTO's and labels
in Fortran can and should be done in C  without  any,  using
compound statements.

7. While Statement; Assignment within  an  Expression; Null
Statement


     The basic looping mechanism in C is  the  while  state-
ment.   Here's a program that copies its input to its output
a character at a time.  Remember that `\0' marks the end  of
file.

     main( ) {
             char c;
             while( (c=getchar( )) != '\0' )
                     putchar(c);
     }


The while statement is a loop, whose general form is

     while (expression) statement

Its meaning is

     (a) evaluate the expression
     (b) if its value is true (i.e., not zero)
                     do the statement, and go back to (a)

Because the expression is tested  before  the  statement  is
executed,  the  statement  part  can be executed zero times,
which is often desirable.   As  in  the  if  statement,  the
expression and the statement can both be arbitrarily compli-
cated, although we haven't seen that yet.  Our example  gets
the  character,  assigns  it  to c, and then tests if it's a
`\0''.  If it is not a `\0', the statement part of the while
is   executed,  printing  the  character.   The  while  then
repeats.  When the input character is finally  a  `\0',  the
while terminates, and so does main.

     Notice that we used an assignment statement

     c = getchar( )

within an expression.  This is a handy  notational  shortcut
which often produces clearer code.  (In fact it is often the
only way to write the code cleanly.   As  an  exercise,  re-
write  the  file-copy  without using an assignment inside an
expression.) It works because an assignment statement has  a
value,  just as any other expression does.  Its value is the
value of the right hand side.  This also implies that we can
use multiple assignments like

     x = y = z = 0;

Evaluation goes from right to left.

     By the way, the extra  parentheses  in  the  assignment
statement  within  the conditional were really necessary: if
we had said

     c = getchar( ) != '\0'

c would be set to 0 or 1 depending on whether the  character
fetched  was  an end of file or not.  This is because in the
absence  of  parentheses  the  assignment  operator  `='  is
evaluated  after  the  relational  operator  `!='.   When in
doubt, or even if not, parenthesize.



Page : << Previous 2  Next >>