Concepts of Programming Languages

(Sean Pound) #1
8.4 Unconditional Branching 375

Instead of a counting loop, Ruby has the upto method. For example, we
could have the following:

1.upto(5) {|x| print x, " "}

This produces the following output:

1 2 3 4 5

Syntax that resembles a for loop in other languages could also be used,
as in the following:

for x in 1..5
print x, " "
end

Ruby actually has no for statement—constructs like the above are converted
by Ruby into upto method calls.
Now we consider how blocks work. The yield statement is similar to a
method call, except that there is no receiver object and the call is a request to
execute the block attached to the method call, rather than a call to a method.
yield is only called in a method that has been called with a block. If the
block has parameters, they are specified in parentheses in the yield state-
ment. The value returned by a block is that of the last expression evaluated
in the block. It is this process that is used to implement the built-in iterators,
such as times.

8.4 Unconditional Branching


An unconditional branch statement transfers execution control to a specified
location in the program. The most heated debate in language design in the late
1960s was over the issue of whether unconditional branching should be part
of any high-level language, and if so, whether its use should be restricted. The
unconditional branch, or goto, is the most powerful statement for controlling
the flow of execution of a program’s statements. However, using the goto care-
lessly can lead to serious problems. The goto has stunning power and great
flexibility (all other control structures can be built with goto and a selector),
but it is this power that makes its use dangerous. Without restrictions on use,
imposed by either language design or programming standards, goto statements
can make programs very difficult to read, and as a result, highly unreliable and
costly to maintain.
These problems follow directly from a goto’s capability of forcing any
program statement to follow any other in execution sequence, regardless of
whether that statement precedes or follows the previously executed statement
in textual order. Readability is best when the execution order of statements is
Free download pdf