We've already seen one of these, the mid-test loop.
One idiomatic thing about that loop is really a sort
of anti-idiom.
Namely, we can't use the switch
statement
to determine the condition upon which to exit the loop.
The reason for this is that the break
keyword is overloaded so that it's meaning in the
switch prevents it from leaving the loop.
The first one is really just an application of the
&&
operator.
for( i = 1; i <= MAX && isend( i ); ++i ) { ... }
isend
that returns
a true value if we've hit the end of the i
's we need to look
at.
One common way this is used is if we're doing something to
each element of a list.
So we'll process the first element, then the second, then the
third and so on.
Now, MAX
is the limit on how big the list may be
and it may well be the case that isend()
is
not defined to return a meaningful value if i > MAX
.
But if we've processed the whole list of MAX
elements, then after the last time through the loop, we'll
come back to test expression 2 with i equal to MAX + 1
.
And we don't want isend()
to be called with
that value for i
.
Here the short-circuiting of &&
saves the day.
In effect, the i <= MAX
guards the call to
isend()
preventing it from being called with
an invalid input.
That same sort of loop can be used in another way as well.
for( i = 1; i <= MAX && isit( i ); ++i ) ; if( i <= MAX ) { ... } else { ... }
isit()
will return true if
the i
th element in the list is the one we're looking for.
Think about a list of students' information and we'll looking
for the GPA of a certain student and are looking that person
up by name.
Notice that the loop has no body; it is followed by a
semicolon.
The if
statement is not in the body of the loop.
That is, the loop doesn't repeat anything, it just has the
side-effect of setting i to identify which element of the list
we were searching for.
And if that element was not in the list, then i
will be greater
than MAX
.
So in the true branch of the if
, we'll put the code
to process the element we found.
The false branch will hold the handling of the error of
not finding what we were looking for.
As you might expect, there are many other common techniques which experienced programmers use without giving them a second thought. While we won't be looking at any more of them here, we did want you to get a sense of what some of these were like.