Here's part of a program that compares two files for equality.
After reading the next line from each file, it checks for the following
conditions:
- Did it reach the end of both files?
- Are the lines different?
- Did I reach the end of just one file?
LOOPread_line (file1, line1, file1_eof);read_line (file2, line2, file2_eof);IF (file1_eof AND file2_eof)THENretval := TRUE;EXIT; -- first timeELSIF (line1 != line2)THENretval := FALSE;EXIT; -- Second time repeatedELSIF (file1_eof OR file2_eof)THENretval := FALSE;EXIT; -- Third time repeatedEND IF;END LOOP;Sometimes it can be difficult to come up with just one EXIT statement.
This usually occurs when we need to check a condition at the beginning
and end of a loop.
We should also be careful to initialize your return value and
your loop terminator variable, to avoid unwanted NULL values that
might disrupt your logic.
Then rewrite this loop body as followsLOOPread_line (file1, line1, file1_eof);read_line (file2, line2, file2_eof);IF (file1_eof AND file2_eof)THENretval := TRUE;exit_loop := TRUE;ELSIF (line1 != line2)THENretval := FALSE;exit_loop := TRUE;ELSIF (file1_eof OR file2_eof)THENretval := FALSE;exit_loop := TRUE;END IF;EXIT WHEN exit_loop; -- Only one timeEND LOOP;
A single EXIT is especially important in large, complex loop bodies;
It allows you to more easily trace and debug your code.
Challenges lies on how badly the loop was written initially,
we may need to perform substantial restructuring to improve the loop
code.

0 comments:
Post a Comment