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) statementIts meaning is
- (a) evaluate the expression (b) if its value is true (i.e., not zero) do the statement, and go back to (a)
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 statementc = 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