Programming in C

(Barry) #1

374 Chapter 17 Miscellaneous and Advanced Features


Programmers who are lazy frequently abuse the gotostatement to branch to other por-
tions of their code.The gotostatement interrupts the normal sequential flow of a pro-
gram. As a result, programs are harder to follow. Using many gotos in a program can
make it impossible to decipher. For this reason,gotostatements are not considered part
of good programming style.

The nullStatement


C permits a solitary semicolon to be placed wherever a normal program statement can
appear.The effect of such a statement, known as the nullstatement, is that nothing is
done. Although this might seem useless, it is often used by C programmers in while,
for,and dostatements. For example, the purpose of the following statement is to store
all the characters read in from the standard input into the character array pointed to by
textuntil a newline character is encountered.
while ( (*text++ = getchar ()) != '\n' )
;
All of the operations are performed inside the looping-conditions part of the while
statement.The nullstatement is needed because the compiler takes the statement that
follows the looping expression as the body of the loop.Without the nullstatement,
whatever statement that follows in the program is treated as the body of the program
loop by the compiler.
The following forstatement copies characters from the standard input to the stan-
dard output until the end of file is encountered:
for ( ; (c = getchar ()) != EOF; putchar (c) )
;
The next forstatement counts the number of characters that appear in the standard
input:
for ( count = 0; getchar () != EOF; ++count )
;
As a final example illustrating the nullstatement, the following loop copies the charac-
ter string pointed to by fromto the one pointed to by to.
while ( (*to++ = *from++) != '\0' )
;
The reader is advised that there is a tendency among certain programmers to try to
squeeze as much as possible into the condition part of the whileor into the condition
or looping part of the for.Try not to become one of those programmers. In general,
only those expressions involved with testing the condition of a loop should be included
inside the condition part. Everything else should form the body of the loop.The only
case to be made for forming such complex expressions might be one of execution effi-
ciency. Unless execution speed is that critical, you should avoid using these types of
expressions.
Free download pdf