Tuesday, April 5, 2011

While Statement; Assignment within an Expression; Null Statement in C

The basic looping mechanism in C is the while statement.  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 complicated, 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 whilethen 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, rewrite 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.Since putchar(c) returns c as its function value, we could also copy the input to the output by nesting the calls to getchar and putchar:
main( ) {
           while( putchar(getchar( )) != '\0' ) ;
   }
What statement is being repeated? None, or technically, the null statement, because all the work is really done within the test part of the while.  This version is slightly different from the previous one, because the final `\0' is copied to the output before we decide to stop.

0 comments:

Post a Comment

Breaking News
Loading...
Quick Message
Press Esc to close
Copyright © 2013 Crack o Hack & tweak STORE All Right Reserved