The next program counts the number of lines in a text file. My version takes advantage of the fact that ReadLn without a parameter list will move the file pointer past the next CR,LF (new line). Thus the program does not even have to know about the intervening chars. The result is a shorter and more elegant program.
Program LineCnt ;
{
count lines in standard input
}
Var
Count : LongInt ;
begin { LineCnt }
Count := 0 ;
while NOT eof do begin
ReadLn ;
Count := Count + 1
end ;
WriteLn (Count:0)
end. { LineCnt }
I declare
Count as a LongInt, a type that K&P did not have access to. I also used LongInt as the counter in CharCnt. It allows the programs to work with much larger files.
As an interesting exercise try omitting the line
Count := 0
which initializes the counter. This should be a bug but I discovered long ago that the programs still work. It apparently is an undocumented feature of Turbo Pascal that integers get initialized to zero by default. Now that I know about it I try never to use it. It goes against the spirit of defensive coding.