The Psychology of Quality and More |
CHAPTER 8 : Language Usage
8.6 Using 'do'There is a problem with the readability of a do loop, in that you do not know what the loop is for until the end of the loop is reached. This contributes to its lack of popularity, although it has a clear use when the body of the loop must be executed at least once. 8.6.1 'do' vs. 'for' or 'while'The problem of reduced readability of the do loop can often be addressed by using a while or for loop to replace it, ensuring that the comparison is always true for at least the first iteration:
do ..could be replaced by.. for ( FileStatus = F_VALID; FileStatus == F_VALID; ) ----------------------------------------------------- However, this is at the cost of clarity of intent - it may not now be clear that the loop is intended to repeat at least once. It also could not be used if FileStatus must enter the loop with a value other than F_VALID. A simple way of keeping the do loop, whilst making it more readable from the beginning, is to comment the do:
do /* UNTIL: FileStatus becomes invalid */
In cases where there is an unclear choice between a while or a do loop, the increased simplicity and clarity of the while makes it preferable. 8.6.2 'do..while' vs. 'repeat..until'The intent of a do loop is often to repeat the loop until a comparison becomes true, rather than false, which the while implies. Pascal's repeat...until loop has the correct logic for this:
/* Beware, this is Pascal! */
To translate this to a do..while format, we must change the comparison:
do
This uses DeMorgan's theorem to reverse the logic of all operators, as while is the logical opposite of until, although the meaning of the comparison is now not as clear. The intent can be clarified by applying the reversal once only, at an outer level:
do ------------------------------------------------------------ This negates the entire original comparison to turn a while into an effective until, enabling the intended comparisons to be used. However, it also adds to the complexity of the statement by adding an extra operator and requiring that while (!(...)) is recognized as meaning until(). This can be simplified by using a macro to redefine the while:
#define UNTIL(a) while (!(a))
This now allows loops which naturally continue until a comparison is met to be more easily and more clearly coded, although at the cost of potential confusion caused by language redefinition.
|
Site Menu |
Quality: | Quality Toolbook | Tools of the Trade | Improvement Encyclopedia | Quality Articles | Being Creative | Being Persuasive | |
And: | C Style (Book) | Stories | Articles | Bookstore | My Photos | About | Contact | |
Settings: | Computer layout | Mobile layout | Small font | Medium font | Large font | Translate | |
You can buy books here |
And the big |