Jump to content

Control flow

From Wikipedia, the free encyclopedia

In software, control flow (or flow of control) describes how execution progresses from one command to the next. In many contexts, such as machine code and an imperative programming language, control progresses sequentially (to the command located immediately after the currently executing command) except when a command transfers control to another point – in which case the command is classified as a control flow command. Depending on context, other terms are used instead of command. For example, in machine code, the typical term is instruction and in an imperative language, the typical term is statement.

Although an imperative language encodes control flow explicitly, languages of other programming paradigms are less focused on control flow. A declarative language specifies desired results without prescribing an order of operations. A functional language uses both language constructs and functions to control flow even though they are usually not called control flow statements.

For a central processing unit (CPU) instruction set, a control flow instruction often alters the program counter and is either an unconditional branch (a.k.a. jump) or a conditional branch. An alternative approach is predication which conditionally enables instructions instead of branching.

An asynchronous control flow transfer such as an interrupt or a signal alters the normal flow of control to a hander before returning control to where it was interrupted.

One way to attack software is to redirect the flow of execution. A variety of control-flow integrity techniques, including stack canaries, buffer overflow protection, shadow stacks, and vtable pointer verification, are used to defend against these attacks.[1][2][3]

Structure

[edit]

Control flow is closely related to code structure. Control flows along lines defined by structure and the execution rules of a language. This general concept of structure is not be confused with structured programming which limits structure to sequencing, selection and iteration based on block organization.

Sequence

[edit]

Sequential execution is the most basic structure. Although not all code is sequential in nature, imperative code is.

Label

[edit]

A label identifies a position in source code. Some control flow statements reference a label so that control jumps to the labeled line. Other than marking a position, a label has no other effect.

Some languages limit a label to a number which is sometimes called a line number although that implies the inherent index of the line; not a label. None-the-less, such numeric labels are typically required to increment from top to bottom in a file even if not be sequential. For example, in BASIC:

10 LET X = 3
20 PRINT X
30 GOTO 10

In other languages, a label is an alphanumeric identifier, usually appearing at the start of a line and immediately followed by a colon. For example, the following C code defines a label Success:

Success: printf("The operation was successful.\n");

Block

[edit]

Most languages provide for organizing sequences of code as a block. When used with a control statement, the beginning of a block provides a jump target. For example, in the following C code (which uses curly braces to delimit a block), control jumps from line 1 to 4 if done is false.

if (done) {
    printf("All done");
} else {
    printf("Still workin' on it");
}

Jump

[edit]

The goto statement is the most basic form of unconditional transfer of control; a jump. Although the keyword may be upper or lower case or one or two words depending on the language, it is like: goto label. When control reaches a goto statement, control then jumps to the statement that follows the indicated label.

The goto statement is been considered harmful by many computer scientists; notably Dijkstra.

Function

[edit]

A function provides for control flow in that when called, execution jumps to the start of the function's code and when it completes, control returns the calling point.

Choice

[edit]

Conditional

[edit]

A conditional statement jumps control based on the value of a Boolean expression. Common variations include:

if-goto
Mimicks a typical machine code instruction; jumps to a label based on a condition.
if-then
Rather than being restricted to a jump, a statement or block can is executed if the expresion is true.
if-then-else
Like the if-then, but with a second action to be performed if the condition is false.
Nested
Conditional statements are often nested inside other conditional statements.
Arithmetic if
Early Fortran, had an arithmetic if (a.k.a. three-way if) that tests whether a numeric value is negative, zero, or positive. This statement was deemed obsolete in Fortran-90, and deleted as of Fortran 2018.
Functional
Some languages have a functional form; for instance Lisp's cond.
Operator
Some languages have an operator form, such as C's ternary operator.
When and unless
Perl supplements a C-style if with when and unless.
Messages
Smalltalk uses ifTrue and ifFalse messages to implement conditionals, rather than a language construct.

Examples

[edit]

In Pascal which is similar syntax as Ada:

if a > 0 then
  writeln("yes")
else
  writeln("no");

In C:

if (a > 0) { 
    puts("yes");
}
else {
    puts("no");
}

In bash:

if [ $a -gt 0 ]; then
      echo "yes"
else
      echo "no"
fi

In Python:

if a > 0: 
    print("yes")
else:
    print("no")

In Lisp:

(princ
  (if (plusp a)
      "yes"
      "no"))

Multiway

[edit]

A multiway branch jumps control based on matching values. There is usually a provision for a default action if no match is found. A switch statement can allow compiler optimizations, such as lookup tables. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching, as in the shell script example on the right, where the *) implements the default case as a glob matching any string. Case logic can also be implemented in functional form, as in SQL's decode statement.

Example

[edit]

In Pascal:

case someChar of
  'a': actionOnA;
  'x': actionOnX;
  'y','z':actionOnYandZ;
  else actionOnNoMatch;
end;

In Ada:

case someChar is
  when 'a' => actionOnA;
  when 'x' => actionOnX;
  when 'y' | 'z' => actionOnYandZ;
  when others => actionOnNoMatch;
end;

In C:

switch (someChar) {
  case 'a': actionOnA; break;
  case 'x': actionOnX; break;
  case 'y':
  case 'z': actionOnYandZ; break;
  default: actionOnNoMatch;
}

In bash:

case $someChar in 
   a)    actionOnA ;;
   x)    actionOnX ;;
   [yz]) actionOnYandZ ;;
   *)    actionOnNoMatch  ;;
esac

In Lisp:

(case some-char
  ((#\a)     action-on-a)
  ((#\x)     action-on-x)
  ((#\y #\z) action-on-y-and-z)
  (else      action-on-no-match))

In Fortran:

select case (someChar)
  case ('a')
    actionOnA
  case ('x')
    actionOnX
  case ('y','z')
    actionOnYandZ
  case default
    actionOnNoMatch
end select

Loop

[edit]
basic types of program loops

A loop is a sequence of statements which is specified once and is executed a number of times based on runtime state. The statements, the loop body, is executed once for each item of a collection (both cases of definite iteration), until a condition is met (indefinite iteration), or infinitely. A loop inside the loop body is called a nested loop.[4][5][6] Early exit from a loop may be supported via a break statement.[7][8]

In functional programming languages, such as Haskell and Scheme, both recursive and iterative processes are expressed with tail recursive procedures instead of looping constructs that are syntactic.

Count-controlled

[edit]

Most programming languages have constructions for repeating a loop a certain number of times. In most cases counting can go downwards instead of upwards and step sizes other than 1 can be used.

 FOR I = 1 TO N
    xxx
 NEXT I
for I := 1 to N do begin
   xxx
end;
 DO I = 1,N
     xxx
 END DO
for ( I=1; I<=N; ++I ) {
    xxx
}

In these examples, if N < 1 then the body of loop may execute once (with I having value 1) or not at all, depending on the programming language.

In many programming languages, only integers can be reliably used in a count-controlled loop. Floating-point numbers are represented imprecisely due to hardware constraints, so a loop such as

   for X := 0.1 step 0.1 to 1.0 do

might be repeated 9 or 10 times, depending on rounding errors and/or the hardware and/or the compiler version. Furthermore, if the increment of X occurs by repeated addition, accumulated rounding errors may mean that the value of X in each iteration can differ quite significantly from the expected sequence 0.1, 0.2, 0.3, ..., 1.0.

Condition-controlled

[edit]

Most programming languages have constructions for repeating a loop until some condition changes. Some variations test the condition at the start of the loop; others test it at the end. If the test is at the start, the body may be skipped completely; if it is at the end, the body is always executed at least once.

DO WHILE (test)
    xxx
LOOP
repeat
    xxx
until test;
while (test) {
    xxx
}
do
    xxx
while (test);

A control break is a value change detection method used within ordinary loops to trigger processing for groups of values. Values are monitored within the loop and a change diverts program flow to the handling of the group event associated with them.

   DO UNTIL (End-of-File)
      IF new-zipcode <> current-zipcode
         display_tally(current-zipcode, zipcount)
         
         current-zipcode = new-zipcode
         zipcount = 0
      ENDIF
      
      zipcount++
   LOOP

Collection-controlled

[edit]

Several programming languages (e.g., Ada, APL, D, C++11, Smalltalk, PHP, Perl, Object Pascal, Java, C#, MATLAB, Visual Basic, Ruby, Python, JavaScript, Fortran 95 and later) have special constructs which allow implicit looping through all elements of an array, or all members of a set or collection.

   someCollection do: [:eachElement |xxx]. "Smalltalk"

   for Item in Collection do begin xxx end;

   foreach (item; myCollection) { xxx }

   foreach someArray { xxx }

   foreach ($someArray as $k => $v) { xxx } # PHP

   Collection<String> coll; for (String s : coll) {}

   foreach (string s in myStringCollection) { xxx }

   someCollection | foreach { $_ } # Powershell: 'foreach' and '%' are the alias of 'ForEach-Object'

   forall ( index = first:last:step... )

Scala has for-expressions, which generalise collection-controlled loops, and also support other uses, such as asynchronous programming. Haskell has do-expressions and comprehensions, which together provide similar function to for-expressions in Scala.

General iteration

[edit]

General iteration constructs such as C's for statement and Common Lisp's do form can be used to express any of the above sorts of loops, and others, such as looping over some number of collections in parallel. Where a more specific looping construct can be used, it is usually preferred over the general iteration construct, since it often makes the purpose of the expression clearer.

Infinite

[edit]

Infinite loops are used to assure a program segment loops forever or until an exceptional condition arises, such as an error. For instance, an event-driven program (such as a server) should loop forever, handling events as they occur, only stopping when the process is terminated by an operator.

Infinite loops can be implemented using other control flow constructs. Most commonly, in unstructured programming this is jump back up (goto), while in structured programming this is an indefinite loop (while loop) set to never end, either by omitting the condition or explicitly setting it to true, as while (true) .... Some languages have special constructs for infinite loops, typically by omitting the condition from an indefinite loop. Examples include Ada (loop ... end loop),[9] Fortran (DO ... END DO), Go (for { ... }), and Ruby (loop do ... end).

Often, an infinite loop is unintentionally created by a programming error in a condition-controlled loop, wherein the loop condition uses variables that never change within the loop.

Continuation with next iteration

[edit]

Sometimes within the body of a loop there is a desire to skip the remainder of the loop body and continue with the next iteration of the loop. Some languages provide a statement such as continue (most languages), skip,[10] cycle (Fortran), or next (Perl and Ruby), which will do this. The effect is to prematurely terminate the innermost loop body and then resume as normal with the next iteration. If the iteration is the last one in the loop, the effect is to terminate the entire loop early.

Redo current iteration

[edit]

Some languages, like Perl[11] and Ruby,[12] have a redo statement that restarts the current iteration from the start.

Restart

[edit]

Ruby has a retry statement that restarts the entire loop from the initial iteration.[13]

Loop-and-a-half

[edit]

Common loop structures sometimes result in duplicated code, either repeated statements or repeated conditions. This arises for various reasons and has various proposed solutions to eliminate or minimize code duplication.[14] Other than the traditional unstructured solution of a goto statement,[15] general structured solutions include having a conditional (if statement) inside the loop (possibly duplicating the condition but not the statements) or wrapping repeated logic in a function (so there is a duplicated function call, but the statements are not duplicated).[14]

A common case is where the start of the loop is always executed, but the end may be skipped on the last iteration.[15] This was dubbed by Dijkstra a loop which is performed "n and a half times",[16] and is now called the loop-and-a-half problem.[8] Common cases include reading data in the first part, checking for end of data, and then processing the data in the second part; or processing, checking for end, and then preparing for the next iteration.[15][8] In these cases, the first part of the loop is executed times, but the second part is only executed times.

This problem has been recognized at least since 1967 by Knuth, with Wirth suggesting solving it via early loop exit.[17] Since the 1990s this has been the most commonly taught solution, using a break statement, as in:[8]

loop
    statements
    if condition break
    statements
repeat

A subtlety of this solution is that the condition is the opposite of a usual while condition: rewriting while condition ... repeat with an exit in the middle requires reversing the condition: loop ... if not condition exit ... repeat. The loop with test in the middle control structure explicitly supports the loop-an-a-half use case, without reversing the condition.[17]

Early exit

[edit]

It is sometimes desirable to stop executing a loop before the end of the body; for example, when using a count-controlled loop to search through a table, one can stop as soon as the required item is found. Early exit is the most common way to solve the loop-and-a-half problem.[8]

Some programming languages provide a statement such as break (most languages), Exit (Visual Basic), or last (Perl), which effect is to terminate the current loop immediately, and transfer control to the statement immediately after that loop.

Other mechanisms for early exit include a return out of a function executing the looped statements, breaking out of both the loop and the function; and raising an exception. There are other proposed control structures, but they are not commonly implemented. This section treats early exit from only the loop ("break").

Most commonly, this is used by combining a conditional (if statement) with an unconditional break, as in Ada:

loop
    Get(X);
    if X = 0 then
        exit;
    end if;
    -- Do something with X.
end loop;

In this form, the condition is interpreted as until. Some languages, such as Ada, have syntax for a conditional break, here an exit when clause (not to be confused with the exitwhen statement in § Proposed control structures); if available, this is more idiomatic:

loop
    Get(X);
    exit when X = 0;
    -- Do something with X.
end loop;

This functions similarly to a loop with test in the middle, but in that case the test is part of the structure of the loop, dividing the body of the loop in half (visually indented at the same level as the start/end of loop), while early exit is unstructured: simply a statement that can appear anywhere in the body of the loop, and in fact multiple break statements are possible.

Python supports conditional execution of code depending on whether a loop was exited early (with a break statement) or not by using an else-clause with the loop. For example,

for n in set_of_numbers:
    if isprime(n):
        print("Set contains a prime number")
        break
else:
    print("Set did not contain any prime numbers")

The else clause in the above example is linked to the for statement, and not the inner if statement. Both Python's for and while loops support such an else clause, which is executed only if early exit of the loop has not occurred.

Multi-level breaks

[edit]

Some languages support breaking out of nested loops; in theory circles, these are called multi-level breaks. One common use example is searching a multi-dimensional table. This can be done either via multilevel breaks (break out of N levels), as in bash[18] and PHP,[19] or via labeled breaks (break out and continue at given label), as in Ada, Go, Java, Rust and Perl.[20] Alternatives to multilevel breaks include single breaks, together with a state variable which is tested to break out another level; exceptions, which are caught at the level being broken out to; placing the nested loops in a function and using return to effect termination of the entire nested loop; or using a label and a goto statement. Neither C nor C++ currently have multilevel break or named loops, and the usual alternative is to use a goto to implement a labeled break.[21] However, the inclusion of this feature has been proposed[22], and was added to C2Y.[23], following the Java syntax. Python does not have a multilevel break or continue – this was proposed in PEP 3136, and rejected on the basis that the added complexity was not worth the rare legitimate use.[24]

The notion of multi-level breaks is of some interest in theoretical computer science, because it gives rise to what is today called the Kosaraju hierarchy.[25] In 1973 S. Rao Kosaraju refined the structured program theorem by proving that it is possible to avoid adding additional variables in structured programming, as long as arbitrary-depth, multi-level breaks from loops are allowed.[26] Furthermore, Kosaraju proved that a strict hierarchy of programs exists: for every integer n, there exists a program containing a multi-level break of depth n that cannot be rewritten as a program with multi-level breaks of depth less than n without introducing added variables.[25]

In his 2004 textbook, David Watt uses Tennent's notion of sequencer to explain the similarity between multi-level breaks and return statements. Watt notes that a class of sequencers known as escape sequencers, defined as "sequencer that terminates execution of a textually enclosing command or procedure", encompasses both breaks from loops (including multi-level breaks) and return statements. As commonly implemented, however, return sequencers may also carry a (return) value, whereas the break sequencer as implemented in contemporary languages usually cannot.[27]

Loop with test in the middle

[edit]

The following structure was proposed by Dahl in 1972:[28]

   loop                           loop
       xxx1                           read(char);
   while test;                    while not atEndOfFile;
       xxx2                           write(char);
   repeat;                        repeat;

The construction here can be thought of as a do loop with the while check in the middle, which allows clear loop-and-a-half logic. Further, by omitting individual components, this single construction can replace several constructions in most programming languages. If xxx1 is omitted, we get a loop with the test at the top (a traditional while loop). If xxx2 is omitted, we get a loop with the test at the bottom, equivalent to a do while loop in many languages. If while is omitted, we get an infinite loop. This construction also allows keeping the same polarity of the condition even when in the middle, unlike early exit, which requires reversing the polarity (adding a not),[17] functioning as until instead of while.

This structure is not widely supported, with most languages instead using if ... break for conditional early exit.

This is supported by some languages, such as Forth, where the syntax is BEGIN ... WHILE ... REPEAT,[29] and the shell script languages Bourne shell (sh) and bash, where the syntax is while ... do ... done or until ... do ... done, as:[30][31]

while
  statement-1
  statement-2
  ...
  condition
do
  statement-a
  statement-b
  ...
done

The shell syntax works because the while (or until) loop accepts a list of commands as a condition,[32] formally:

 while test-commands; do consequent-commands; done

The value (exit status) of the list of test-commands is the value of the last command, and these can be separated by newlines, resulting in the idiomatic form above.

Similar constructions are possible in C and C++ with the comma operator, and other languages with similar constructs, which allow shoehorning a list of statements into the while condition:

while (
  statement_1,
  statement_2,
  condition
) {
  statement_a;
  statement_b;
}

While legal, this is marginal, and it is primarily used, if at all, only for short modify-then-test cases, as in:[33]

while (read_string(s), strlen(s) > 0) {
  // ...
}

Loop variants and invariants

[edit]

Loop variants and loop invariants are used to express correctness of loops.[34]

In practical terms, a loop variant is an integer expression which has an initial non-negative value. The variant's value must decrease during each loop iteration but must never become negative during the correct execution of the loop. Loop variants are used to guarantee that loops will terminate.

A loop invariant is an assertion which must be true before the first loop iteration and remain true after each iteration. This implies that when a loop terminates correctly, both the exit condition and the loop invariant are satisfied. Loop invariants are used to monitor specific properties of a loop during successive iterations.

Some programming languages, such as Eiffel contain native support for loop variants and invariants. In other cases, support is an add-on, such as the Java Modeling Language's specification for loop statements in Java.

Loop sublanguage

[edit]

Some Lisp dialects provide an extensive sublanguage for describing Loops. An early example can be found in Conversional Lisp of Interlisp. Common Lisp[35] provides a Loop macro which implements such a sublanguage.

Loop system cross-reference table

[edit]
Programming language conditional loop early exit loop continuation redo retry correctness facilities
begin middle end count collection general infinite [1] variant invariant
Ada Yes Yes Yes Yes arrays No Yes deep nested No
APL Yes No Yes Yes Yes Yes Yes deep nested [3] Yes No No
C Yes No Yes No [2] No Yes No deep nested [3] deep nested [3] No
C++ Yes No Yes No [2] Yes [9] Yes No deep nested [3] deep nested [3] No
C# Yes No Yes No [2] Yes Yes No deep nested [3] deep nested [3]
COBOL Yes No Yes Yes No Yes No deep nested [15] deep nested [14] No
Common Lisp Yes Yes Yes Yes builtin only [16] Yes Yes deep nested No
D Yes No Yes Yes Yes Yes Yes[14] deep nested deep nested No
Eiffel Yes No No Yes [10] Yes Yes No one level [10] No No No [11] integer only [13] Yes
F# Yes No No Yes Yes No No No [6] No No
FORTRAN 77 Yes No No Yes No No No one level Yes No No
Fortran 90 Yes No No Yes No No Yes deep nested deep nested No No
Fortran 95 and later Yes No No Yes arrays No Yes deep nested deep nested No No
Go Yes No No Yes builtin only Yes Yes deep nested deep nested No
Haskell No No No No Yes No Yes No [6] No No
Java Yes No Yes No [2] Yes Yes No deep nested deep nested No non-native [12] non-native [12]
JavaScript Yes No Yes No [2] Yes Yes No deep nested deep nested No
Natural Yes Yes Yes Yes No Yes Yes Yes Yes Yes No
OCaml Yes No No Yes arrays,lists No No No [6] No No
PHP Yes No Yes No [2] [5] Yes [4] Yes No deep nested deep nested No
Perl Yes No Yes No [2] [5] Yes Yes No deep nested deep nested Yes
Python Yes No No No [5] Yes No No deep nested [6] deep nested [6] No
Rebol No [7] Yes Yes Yes Yes No [8] Yes one level [6] No No
Ruby Yes No Yes Yes Yes No Yes deep nested [6] deep nested [6] Yes Yes
Rust Maybe Maybe Maybe Maybe Maybe Maybe Maybe Maybe Maybe Maybe Maybe
Standard ML Yes No No No arrays,lists No No No [6] No No
Visual Basic .NET Yes No Yes Yes Yes No Yes one level per type of loop one level per type of loop
PowerShell Yes No Yes No [2] Yes Yes No Yes Yes
  1. a while (true) does not count as an infinite loop for this purpose, because it is not a dedicated language structure.
  2. a b c d e f g h C's for (init; test; increment) loop is a general loop construct, not specifically a counting one, although it is often used for that.
  3. a b c Deep breaks may be accomplished in APL, C, C++ and C# through the use of labels and gotos.
  4. a Iteration over objects was added in PHP 5.
  5. a b c A counting loop can be simulated by iterating over an incrementing list or generator, for instance, Python's range().
  6. a b c d e Deep breaks may be accomplished through the use of exception handling.
  7. a There is no special construct, since the while function can be used for this.
  8. a There is no special construct, but users can define general loop functions.
  9. a The C++11 standard introduced the range-based for. In the STL, there is a std::for_each template function which can iterate on STL containers and call a unary function for each element.[36] The functionality also can be constructed as macro on these containers.[37]
  10. a Count-controlled looping is effected by iteration across an integer interval; early exit by including an additional condition for exit.
  11. a Eiffel supports a reserved word retry, however it is used in exception handling, not loop control.
  12. a Requires Java Modeling Language (JML) behavioral interface specification language.
  13. a Requires loop variants to be integers; transfinite variants are not supported. Eiffel: Why loop variants are integers
  14. a D supports infinite collections, and the ability to iterate over those collections. This does not require any special construct.
  15. a Deep breaks can be achieved using GO TO and procedures.
  16. a Common Lisp predates the concept of generic collection type.

Non-local

[edit]

Many programming languages, especially those favoring more dynamic styles of programming, offer constructs for non-local control flow. These cause the flow of execution to jump out of a given context and resume at some predeclared point. Conditions, exceptions and continuations are three common sorts of non-local control constructs; more exotic ones also exist, such as generators, coroutines and the async keyword.

Condition

[edit]

The earliest Fortran compilers had statements for testing exceptional conditions. These included the IF ACCUMULATOR OVERFLOW, IF QUOTIENT OVERFLOW, and IF DIVIDE CHECK statements. In the interest of machine independence, they were not included in FORTRAN IV and the Fortran 66 Standard. However since Fortran 2003 it is possible to test for numerical issues via calls to functions in the IEEE_EXCEPTIONS module.

PL/I has some 22 standard conditions (e.g., ZERODIVIDE SUBSCRIPTRANGE ENDFILE) which can be raised and which can be intercepted by: ON condition action; Programmers can also define and use their own named conditions.

Like the unstructured if, only one statement can be specified so in many cases a GOTO is needed to decide where flow of control should resume.

Unfortunately, some implementations had a substantial overhead in both space and time (especially SUBSCRIPTRANGE), so many programmers tried to avoid using conditions.

Common Syntax examples:

 ON condition GOTO label

Exception

[edit]

Modern languages have a specialized structured construct for exception handling which does not rely on the use of GOTO or (multi-level) breaks or returns. For example, in C++ one can write:

try {
    xxx1                                  // Somewhere in here
    xxx2                                  //     use: '''throw''' someValue;
    xxx3
} catch (someClass& someId) {             // catch value of someClass
    actionForSomeClass 
} catch (someType& anotherId) {           // catch value of someType
    actionForSomeType
} catch (...) {                           // catch anything not already caught
    actionForAnythingElse
}

Any number and variety of catch clauses can be used above. If there is no catch matching a particular throw, control percolates back through function calls and/or nested blocks until a matching catch is found or until the end of the main program is reached, at which point the program is forcibly stopped with a suitable error message.

Via C++'s influence, catch is the keyword reserved for declaring a pattern-matching exception handler in other languages popular today, like Java or C#. Some other languages like Ada use the keyword exception to introduce an exception handler and then may even employ a different keyword (when in Ada) for the pattern matching. A few languages like AppleScript incorporate placeholders in the exception handler syntax to automatically extract several pieces of information when the exception occurs. This approach is exemplified below by the on error construct from AppleScript:

try
    set myNumber to myNumber / 0
on error e  number n  from f  to t  partial result pr
    if ( e = "Can't divide by zero" ) then display dialog "You must not do that"
end try

David Watt's 2004 textbook also analyzes exception handling in the framework of sequencers (introduced in this article in the section on early exits from loops). Watt notes that an abnormal situation, generally exemplified with arithmetic overflows or input/output failures like file not found, is a kind of error that "is detected in some low-level program unit, but [for which] a handler is more naturally located in a high-level program unit". For example, a program might contain several calls to read files, but the action to perform when a file is not found depends on the meaning (purpose) of the file in question to the program and thus a handling routine for this abnormal situation cannot be located in low-level system code. Watts further notes that introducing status flags testing in the caller, as single-exit structured programming or even (multi-exit) return sequencers would entail, results in a situation where "the application code tends to get cluttered by tests of status flags" and that "the programmer might forgetfully or lazily omit to test a status flag. In fact, abnormal situations represented by status flags are by default ignored!" Watt notes that in contrast to status flags testing, exceptions have the opposite default behavior, causing the program to terminate unless the program deals with the exception explicitly in some way, possibly by adding explicit code to ignore it. Based on these arguments, Watt concludes that jump sequencers or escape sequencers are less suitable as a dedicated exception sequencer with the semantics discussed above.[38]

In Object Pascal, D, Java, C#, and Python a finally clause can be added to the try construct. No matter how control leaves the try the code inside the finally clause is guaranteed to execute. This is useful when writing code that must relinquish an expensive resource (such as an opened file or a database connection) when finished processing:

FileStream stm = null;                    // C# example
try
{
    stm = new FileStream("logfile.txt", FileMode.Create);
    return ProcessStuff(stm);             // may throw an exception
} 
finally
{
    if (stm != null)
        stm.Close();
}

Since this pattern is fairly common, C# has a special syntax:

using (var stm = new FileStream("logfile.txt", FileMode.Create))
{
    return ProcessStuff(stm); // may throw an exception
}

Upon leaving the using-block, the compiler guarantees that the stm object is released, effectively binding the variable to the file stream while abstracting from the side effects of initializing and releasing the file. Python's with statement and Ruby's block argument to File.open are used to similar effect.

All the languages mentioned above define standard exceptions and the circumstances under which they are thrown. Users can throw exceptions of their own; C++ allows users to throw and catch almost any type, including basic types like int, whereas other languages like Java are less permissive.

Continuation

[edit]

Async

[edit]

C# 5.0 introduced the async keyword for supporting asynchronous I/O in a "direct style".

Generator

[edit]

Generators, also known as semicoroutines, allow control to be yielded to a consumer method temporarily, typically using a yield keyword (yield description) . Like the async keyword, this supports programming in a "direct style".

Coroutine

[edit]

Coroutines are functions that can yield control to each other - a form of co-operative multitasking without threads.

Coroutines can be implemented as a library if the programming language provides either continuations or generators - so the distinction between coroutines and generators in practice is a technical detail.

COMEFROM

[edit]

In a spoof Datamation article[39] in 1973, R. Lawrence Clark suggested that the GOTO statement could be replaced by the COMEFROM statement, and provides some entertaining examples. COMEFROM was implemented in one esoteric programming language named INTERCAL.

Event-based early exit from nested loop

[edit]

This construct was proposed by Zahn in 1974,[40] and discussed in Knuth (1974). A modified version is presented here.

   exitwhen EventA or EventB or EventC;
       xxx
   exits
       EventA: actionA
       EventB: actionB
       EventC: actionC
   endexit;

exitwhen is used to specify the events which may occur within xxx, their occurrence is indicated by using the name of the event as a statement. When some event does occur, the relevant action is carried out, and then control passes just after endexit. This construction provides a very clear separation between determining that some situation applies, and the action to be taken for that situation.

exitwhen is conceptually similar to exception handling, and exceptions or similar constructs are used for this purpose in many languages.

The following simple example involves searching a two-dimensional table for a particular item.

   exitwhen found or missing;
       for I := 1 to N do
           for J := 1 to M do
               if table[I,J] = target then found;
       missing;
   exits
       found:   print ("item is in table");
       missing: print ("item is not in table");
   endexit;

See also

[edit]

Notes

[edit]

References

[edit]
  1. ^ Payer, Mathias; Kuznetsov, Volodymyr. "On differences between the CFI, CPS, and CPI properties". nebelwelt.net. Retrieved 2016-06-01.
  2. ^ "Adobe Flash Bug Discovery Leads To New Attack Mitigation Method". Dark Reading. 10 November 2015. Retrieved 2016-06-01.
  3. ^ Endgame. "Endgame to Present at Black Hat USA 2016". www.prnewswire.com (Press release). Retrieved 2016-06-01.
  4. ^ "Nested Loops in C with Examples". GeeksforGeeks. 2019-11-25. Retrieved 2024-03-14.
  5. ^ "Python Nested Loops". www.w3schools.com. Retrieved 2024-03-14.
  6. ^ Dean, Jenna (2019-11-22). "Nested Loops". The Startup. Retrieved 2024-03-14.
  7. ^ Knuth, Donald E. (1974). "Structured Programming with go to Statements". Computing Surveys. 6 (4): 261–301. CiteSeerX 10.1.1.103.6084. doi:10.1145/356635.356640. S2CID 207630080.
  8. ^ a b c d e Roberts, E. [1995] "Loop Exits and Structured Programming: Reopening the Debate Archived 2014-07-25 at the Wayback Machine," ACM SIGCSE Bulletin, (27)1: 268–272.
  9. ^ Ada Programming: Control: Endless Loop
  10. ^ "What is a loop and how we can use them?". Archived from the original on 2020-07-28. Retrieved 2020-05-25.
  11. ^ "redo - perldoc.perl.org". perldoc.perl.org. Retrieved 2020-09-25.
  12. ^ "control_expressions - Documentation for Ruby 2.4.0". docs.ruby-lang.org. Retrieved 2020-09-25.
  13. ^ "control_expressions - Documentation for Ruby 2.3.0". docs.ruby-lang.org. Retrieved 2020-09-25.
  14. ^ a b "Messy Loop Conditions". WikiWikiWeb. 2014-11-03.
  15. ^ a b c Knuth 1974, p. 278, Simple Iterations.
  16. ^ Edsger W. Dijkstra, personal communication to Donald Knuth on 1974-01-03, cited in Knuth (1974, p. 278, Simple Iterations)
  17. ^ a b c Knuth 1974, p. 279.
  18. ^ Advanced Bash Scripting Guide: 11.3. Loop Control
  19. ^ PHP Manual: "break"
  20. ^ perldoc: last
  21. ^ comp.lang.c FAQ list · "Question 20.20b"
  22. ^ "named-loops". open-std.org. 18 September 2024.
  23. ^ "Information technology — Programming languages — C" (PDF). open-std.org. 4 May 2025.
  24. ^ [Python-3000] Announcing PEP 3136, Guido van Rossum
  25. ^ a b Kozen, Dexter (2008). "The Böhm–Jacopini Theorem is False, Propositionally". Mathematics of Program Construction (PDF). Lecture Notes in Computer Science. Vol. 5133. pp. 177–192. CiteSeerX 10.1.1.218.9241. doi:10.1007/978-3-540-70594-9_11. ISBN 978-3-540-70593-2.
  26. ^ Kosaraju, S. Rao. "Analysis of structured programs," Proc. Fifth Annual ACM Syrup. Theory of Computing, (May 1973), 240-252; also in J. Computer and System Sciences, 9, 3 (December 1974), cited by Knuth (1974).
  27. ^ David Anthony Watt; William Findlay (2004). Programming language design concepts. John Wiley & Sons. pp. 215–221. ISBN 978-0-470-85320-7.
  28. ^ Dahl & Dijkstra & Hoare, "Structured Programming" Academic Press, 1972.
  29. ^ "6. Throw It For a Loop".
  30. ^ "3.2.5.1 Looping Constructs", The GNU Bash Reference Manual, 2025-05-18
  31. ^ "How could a language make the loop-and-a-half less error-prone?". Stack Exchange: Programming Language Design and Implementation.
  32. ^ "3.2.4 Lists of Commands", The GNU Bash Reference Manual, 2025-05-18
  33. ^ "What does the comma operator , do?". Stack Overflow.
  34. ^ Meyer, Bertrand (1991). Eiffel: The Language. Prentice Hall. pp. 129–131.
  35. ^ "Common Lisp LOOP macro".
  36. ^ for_each. Sgi.com. Retrieved on 2010-11-09.
  37. ^ Chapter 1. Boost.Foreach Archived 2010-01-29 at the Wayback Machine. Boost-sandbox.sourceforge.net (2009-12-19). Retrieved on 2010-11-09.
  38. ^ David Anthony Watt; William Findlay (2004). Programming language design concepts. John Wiley & Sons. pp. 221–222. ISBN 978-0-470-85320-7.
  39. ^ We don't know where to GOTO if we don't know where we've COME FROM. This (spoof) linguistic innovation lives up to all expectations. Archived 2018-07-16 at the Wayback Machine By R. Lawrence Clark* From Datamation, December, 1973
  40. ^ Zahn, C. T. "A control statement for natural top-down structured programming" presented at Symposium on Programming Languages, Paris, 1974.

Further reading

[edit]
  • Hoare, C. A. R. "Partition: Algorithm 63," "Quicksort: Algorithm 64," and "Find: Algorithm 65." Comm. ACM 4, 321–322, 1961.
[edit]