All Topics  
Control flow

 

   Email Print
   Bookmark   Link






 

Control flow



 
 
In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
 control flow (or alternatively, flow of control) refers to the order in which the individual statements
Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements....
, instructions
Instruction (computer science)

In computer science, an instruction is a single operation of a central processing unit defined by an instruction set architecture. In a broader sense, an "instruction" may be any representation of an element of an executable program, such as a bytecode....
 or function calls of an imperative
Imperative programming

In computer science, imperative programming is a programming paradigm that describes computation in terms of statement s that change a program state ....
 or functional
Functional programming

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of function s and avoids program state and immutable object data....
 program
Computer program

Computer programs are Instruction for a computer. A computer requires programs to function. Moreover, a computer program does not run unless its instructions are executed by a Central processing unit; however, a program may communicate an Algorithm#Formalization of algorithms to people without running....
 are executed
Execution (computers)

Execution in computer engineering and software engineering is the Process by which a computer or a virtual machine carries out the instructions of a computer program....
 or evaluated.

Within an imperative programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
, a control flow statement is a statement whose execution results in a decision being made as to which of two or more control flows should be followed. For non-strict
Strict programming language

A strict programming language is one in which only strict functions may be defined by the user. A non-strict programming language is one that allows the user to define non-strict functions, and hence may allow lazy evaluation....
 functional languages, functions and language constructs exist to achieve the same ends, but they are not necessarily called control flow statements.

The kinds of control flow statements supported by different languages vary, but can be categorized by their effect:



Interrupt
Interrupt

In computing, an interrupt is an asynchronous communication signal from hardware indicating the need for attention or a synchronous event in software indicating the need for a change in execution....
s and signals
Signal (computing)

A signal is a limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems. Essentially it is an asynchronous notification sent to a Process in order to notify it of an event that occurred....
 are low-level mechanisms that can alter the flow of control in a way similar to a subroutine, but usually occur as a response to some external stimulus or event rather than execution of a control flow statement.






Discussion
Ask a question about 'Control flow'
Start a new discussion about 'Control flow'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In computer science
Computer science

Computer science is the study of the theoretical foundations of information and computation, and of practical techniques for their implementation and application in computer systems....
 control flow (or alternatively, flow of control) refers to the order in which the individual statements
Statement (programming)

In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements....
, instructions
Instruction (computer science)

In computer science, an instruction is a single operation of a central processing unit defined by an instruction set architecture. In a broader sense, an "instruction" may be any representation of an element of an executable program, such as a bytecode....
 or function calls of an imperative
Imperative programming

In computer science, imperative programming is a programming paradigm that describes computation in terms of statement s that change a program state ....
 or functional
Functional programming

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of function s and avoids program state and immutable object data....
 program
Computer program

Computer programs are Instruction for a computer. A computer requires programs to function. Moreover, a computer program does not run unless its instructions are executed by a Central processing unit; however, a program may communicate an Algorithm#Formalization of algorithms to people without running....
 are executed
Execution (computers)

Execution in computer engineering and software engineering is the Process by which a computer or a virtual machine carries out the instructions of a computer program....
 or evaluated.

Within an imperative programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
, a control flow statement is a statement whose execution results in a decision being made as to which of two or more control flows should be followed. For non-strict
Strict programming language

A strict programming language is one in which only strict functions may be defined by the user. A non-strict programming language is one that allows the user to define non-strict functions, and hence may allow lazy evaluation....
 functional languages, functions and language constructs exist to achieve the same ends, but they are not necessarily called control flow statements.

The kinds of control flow statements supported by different languages vary, but can be categorized by their effect:

  • continuation at a different statement (jump
    Branch (computer science)

    A branch is a point in a computer program where the flow of control is altered. The term branch is usually used when referring to a program written in machine code or assembly language; in a high-level programming language, branches usually take the form of conditional statements, subroutine calls or GOTO statements....
    ),
  • executing a set of statements only if some condition is met (choice),
  • executing a set of statements zero or more times, until some condition is met (loop),
  • executing a set of distant statements, after which the flow of control may possibly return (subroutine
    Subroutine

    In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
    s, coroutine
    Coroutine

    In computer science, coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming of execution at certain locations....
    s, and continuation
    Continuation

    In computing and programming, a continuation is an abstract representation of Control flow, or the "rest of computation" or "rest of code to be executed"....
    s),
  • stopping the program, preventing any further execution (halt).


Interrupt
Interrupt

In computing, an interrupt is an asynchronous communication signal from hardware indicating the need for attention or a synchronous event in software indicating the need for a change in execution....
s and signals
Signal (computing)

A signal is a limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems. Essentially it is an asynchronous notification sent to a Process in order to notify it of an event that occurred....
 are low-level mechanisms that can alter the flow of control in a way similar to a subroutine, but usually occur as a response to some external stimulus or event rather than execution of a control flow statement. Self-modifying code
Self-modifying code

In computer science, self-modifying code is Code that alters its own Instruction while it is Execution - usually to reduce the instruction path length and improve performance....
 can also be used to affect control flow through its side effects
Side effect (computer science)

In computer science, a subroutine or expression is said to produce a side effect if it modifies some state_ in addition to returning a value. For example, a function might modify a global or a static variable, modify one of its arguments, write data to a display or file, or read some data from other side-effecting functions....
, but usually does not involve an explicit control flow statement (an exception being the ALTER verb in COBOL
COBOL

COBOL is one of the oldest programming languages still in active use. Its name is an acronym for COmmon Business-Oriented Language, defining its primary domain in business, finance, and administrative systems for companies and governments....
).

At the level of machine or assembly language
Assembly language

An assembly language is a low-level language for programming computers. It implements a symbolic representation of the numeric machine codes and other constants needed to program a particular CPU architecture....
, control flow instructions usually work by altering the program counter
Program counter

The program counter, or PC is a processor register that indicates where the computer is in its instruction sequence. Depending on the details of the particular computer, the PC holds either the address of the instruction being executed, or the address of the next instruction to be executed....
. For some CPUs
Central processing unit

A central processing unit is an electronic circuit that can execute computer programs. This broad definition can easily be applied to many early computers that existed long before the term "CPU" ever came into widespread usage....
 the only control flow instructions available are conditional or unconditional branch
Branch (computer science)

A branch is a point in a computer program where the flow of control is altered. The term branch is usually used when referring to a program written in machine code or assembly language; in a high-level programming language, branches usually take the form of conditional statements, subroutine calls or GOTO statements....
es (sometimes called jumps).

Primitives


Labels

A label
Label (programming language)

A label in a programming language is a sequence of characters that identifies a location within source code. In most languages labels take the form of an identifier, often followed by a punctuation ....
 is an explicit name or number assigned to a fixed position within the source code
Source code

In computer science, source code is any collection of statements or declarations written in some human-readable computer programming language....
, and which may be referenced by control flow statements appearing elsewhere in the source code. Other than marking a position within the source code a label has no effect.

Line number
Line number

In computing, a line number is a method used to specify a particular sequence of characters in a text file. The most common method of assigning numbers to lines is to assign every line a unique number, starting at 1 for the first line, and incrementing by 1 for each successive line....
s are a kind of label used in some languages (e.g. Fortran
Fortran

Fortran is a general-purpose programming language, procedural programming language, imperative programming language programming language that is especially suited to numerical analysis and scientific computing....
 and BASIC), which are whole number
Whole number

The term whole number is used by various authors to mean either:*the nonnegative integer *the positive integer *all integer ...
s placed at the beginning of each line of text within the source code. Languages which use line numbers often impose the constraint that the line numbers must increase in value in each subsequent line, but may not require that they be consecutive. For example, in BASIC:

10 LET X = 3 20 PRINT X

In other languages such as C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
 and Ada a label is an identifier
Identifier

In computer science, Identifiers are Lexical Token s that name entity. The concept is analogy to that of a "name". Identifiers are used extensively in virtually all information processing systems....
, usually appearing at the beginning of a line and immediately followed by a colon. For example, in C:

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

The Algol 60 language allowed both whole numbers and identifiers as labels (both attached by colons to the following statement), but few if any other variants of Algol allowed whole numbers.

Goto


The goto statement (a combination of the English words go and to, and pronounced accordingly) is the most basic form of unconditional transfer of control.

Although the keyword may either be in upper or lower case depending on the language, it is usually written as: goto label The effect of a goto statement is to cause the next statement to be executed to always be the statement appearing immediately after (or at) the indicated label.

Goto statements have been considered harmful
Considered harmful

In computer science and related disciplines, considered harmful is a phrase popularly used in the titles of diatribes and other critical essays ....
 by many computer scientists, notably Dijkstra.

Subroutines


The terminology for subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
s varies; they may alternatively be known as routines, procedures, functions (especially if they return results) or methods (especially if they belong to classes or type class
Type class

In computer science, a type class is a type system construct that supports Type polymorphism#Ad-hoc polymorphism. This is achieved by adding constraints to type variables in Parametric polymorphism#Parametric polymorphism types....
es).

In the 1950s, computer memories were very small by current standards so subroutines were used primarily to reduce program size; a piece of code was written once and then used many times from various other places in the program.

Nowadays, subroutines are more frequently used to help make a program more structured, e.g. by isolating some particular algorithm or hiding some particular data access method. If many programmers are working on a single program, subroutines are one kind of modularity
Modularity (programming)

Modular programming is a software design technique that increases the extent to which software is composed from separate parts, called modules. Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components....
 that can help split up the work.

Minimal structured control flow


(See also Structured program theorem
Structured program theorem

The structured program theorem is a result in programming language theory. It states that every computable function can be implemented in a programming language that combines subprograms in only three specific ways....
.) In May 1966, Böhm and Jacopini published an article in Communications of the ACM which showed that any program with gotos could be transformed into a goto-free form involving only choice (IF THEN ELSE) and loops (WHILE condition DO xxx), possibly with duplicated code and/or the addition of Boolean variables (true/false flags). Later authors have shown that choice can be replaced by loops (and yet more Boolean variables).

The fact that such minimalism is possible does not necessarily mean that it is desirable; after all, computers theoretically only need one machine instruction
One instruction set computer

A One Instruction Set Computer is a Turing-complete abstract machine that uses only one instruction . These universal computers are used primarily as a theoretical teaching aid ....
 (subtract one number from another and branch if the result is negative), but practical computers have dozens or even hundreds of machine instructions.

What Böhm and Jacopini's article showed was that all programs could be goto-free. Other research showed that control structures with one entry and one exit were much easier to understand than any other form, primarily because they could be used anywhere as a statement without disrupting the control flow. In other words, they were composable. (Later developments, such as non-strict programming languages - and more recently, composable software transactions
Software transactional memory

In computer science, software transactional memory is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing....
 - have continued this line of thought, making components of programs even more freely composable.)

Control structures in practice

Most programming languages with control structures have an initial keyword which indicates the type of control structure involved. Languages then divide as to whether or not control structures have a final keyword.

  • No final keyword: Algol 60, C
    C (programming language)

    C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
    , C++
    C++

    C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
    , Haskell
    Haskell (programming language)

    Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
    , Java
    Java (programming language)

    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
    , Pascal, Perl
    Perl

    In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
    , PHP
    PHP

    PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
    , PL/I, Python
    Python (programming language)

    Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
    , PowerShell
    Windows PowerShell

    Windows PowerShell is an extensible command line interface shell and associated scripting language from Microsoft. It was released in 2006 and is currently available for Windows XP SP2/SP3, Windows Server 2003, Windows Vista and is included in Windows Server 2008 as well as Windows 7 as an optional feature....
    . Such languages need some way of grouping statements together:
    • Algol 60 and Pascal : begin ... end
    • C, C++, Java, Perl, PHP, and PowerShell: curly brackets
      Curly bracket programming language

      Curly brace or bracket programming languages are those which use balanced brackets to make block s in their syntax or formal grammar, mainly due to being C -influenced....
       
    • PL/1: DO ... END
    • Python: uses indentation level (see Off-side rule
      Off-side rule

      A computer programming language is said to adhere to the off-side rule if in it the scope of declarations is expressed by their indentation, i.e., blocks are formed via indentation....
      )
    • Haskell: either indentation level or curly brackets can be used, and they can be freely mixed
  • Final keyword: Ada, Algol 68
    ALGOL 68

    ALGOL 68 is an imperative programming computer programming programming language that was conceived as a successor to the ALGOL 60 programming language, designed with the goal of a much wider scope of application and more rigorously defined syntax and semantics....
    , Modula-2
    Modula-2

    Modula-2 is a computer programming language invented by Niklaus Wirth at ETH, around 1978, as a successor to his intermediate language Modula. Modula-2 was implemented in 1980 for the Lilith computer, which was commercialized in 1982 by startup company DISER as MC1 and MC2....
    , Fortran 77
    Fortran

    Fortran is a general-purpose programming language, procedural programming language, imperative programming language programming language that is especially suited to numerical analysis and scientific computing....
    , Visual Basic
    Visual Basic

    'Visual Basic' is the third-generation programming language event-driven programming and integrated integrated development environment from Microsoft for its Component Object Model programming model....
    . The forms of the final keyword vary:
    • Ada: final keyword is end + space + initial keyword e.g. if ... end if, loop ... end loop
    • Algol 68: initial keyword spelled backwards e.g. if ... fi, case ... esac
    • Fortran 77: final keyword is end + initial keyword e.g. IF ... ENDIF, DO ... ENDDO
    • Modula-2: same final keyword end for everything
    • Visual Basic: every control structure has its own keyword. If ... End If; For ... Next; Do ... Loop


Choice


Loops


A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code "inside" the loop (the body of the loop, shown below as xxx) is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met.

In some languages, such as Scheme, loops are often expressed using tail recursion
Tail recursion

In computer science, tail recursion is a special case of Recursion_ in which the last operation of the function, the tail call, is a recursive call....
 rather than explicit looping constructs.

Count-controlled loops


Most programming languages have constructions for repeating a loop a certain number of times. Note that if N is less than 1 in these examples then the language may specify that the body is skipped completely, or that the body is executed just once with N = 1. In most cases counting can go downwards instead of upwards and step sizes other than 1 can be used.

FOR I = 1 TO N for I := 1 to N do begin xxx xxx NEXT I end;

DO I = 1,Nfor ( I=1; I<=N; ++I )

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 loops


Again, most programming languages have constructions for repeating a loop until some condition changes. Note that some variations place the test at the start of the loop, while others have the test at the end of the loop. In the former case the body may be skipped completely, while in the latter case the body is always obeyed at least once.

DO WHILE (test) repeat xxx xxx LOOP until test;

while (test) while (test);

Collection-controlled loops

Several programming languages (e.g. Ada, Smalltalk
Smalltalk

Smalltalk is an Object-oriented programming, Type system, reflection computer programming programming language. Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human?computer symbiosis." It was designed and created in part for educational use, more so for constructionist learning, at PARC by Al...
, Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
, Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
, C#, Visual Basic
Visual Basic

'Visual Basic' is the third-generation programming language event-driven programming and integrated integrated development environment from Microsoft for its Component Object Model programming model....
, Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
, Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
, JavaScript
JavaScript

JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
) have special constructs which allow implicitly looping through all elements of an array, or all members of a set or collection.

someCollection do: [:eachElement |xxx].

foreach someArray

Collection coll; for (String s : coll)

foreach (string s in myStringCollection)

$someCollection | ForEach-Object

General iteration

General iteration constructs such as C's for statement and Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
's do form can be used to express any of the above sorts of loops, as well as others -- such as looping over a 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 more clear.

Infinite loop
Infinite loop

An infinite loop is a sequence of instructions in a computer program which control flow#Loops endlessly, either due to the loop having no terminating condition or having one that can never be met....
s

Sometimes it is desirable for a program to loop forever, or until an exceptional condition such as an error arises. For instance, an event-driven program (such as a server
Server (computing)

A server is a computer program that provides services to other computer programs , in the same or other computer. The physical computer that runs a server program is also often referred to as server....
) may be intended to loop forever handling events as they occur, only stopping when the process is killed by the operator.

Often, an infinite loop is due to a programming error in a condition-controlled loop, wherein the loop condition is never changed within the loop.

Continuation with next iteration


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, skip, or next 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


Some languages, like Perl and Ruby, have a redo statement that restarts the current iteration from the beginning.

Early exit from loops


When using a count-controlled loop to search through a table, it might be desirable to stop searching as soon as the required item is found. Some programming languages provide a statement such as break or exit, whose effect is to terminate the current loop immediately and transfer control to the statement immediately following that loop. Things can get a bit messy if searching a multi-dimensional table using nested loops (see Missing Control Structures below).

The following example is done in Ada which supports both early exit from loops
Control flow

In computer science control flow refers to the order in which the individual statement , Instruction or function calls of an imperative programming or functional programming computer program are execution or evaluated....
 and loops with test in the middle
Control flow

In computer science control flow refers to the order in which the individual statement , Instruction or function calls of an imperative programming or functional programming computer program are execution or evaluated....
. Both features are very similar and comparing both code snippets will show the difference: early exit needs to be combined with an if statement while a condition in the middle is a self contained construct.

with Ada.Text IO; with Ada.Integer Text IO;

procedure Print_Squares is X : Integer; begin Read_Data : loop Ada.Integer Text IO.Get(X); exit Read_Data when X = 0; Ada.Text IO.Put (X * X); Ada.Text IO.New_Line; end loop Read_Data; end Print_Squares;

Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
 supports conditional execution of code depending on whether a loop was exited early (with a break statement) or not by using a 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"

Note that the else clause in the above example is attached 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 did not occur.

Loop system cross reference table


Programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
conditional loop early exit continuation redo
begin middle end count collection general
Ada  
C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
C#  
Common Lisp
Common Lisp

Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in American National Standards Institute standard document Information Technology - Programming Language - Common Lisp, formerly X3.226-1994 ....
 
FORTRAN 77  
Fortran 90  
Haskell
Haskell (programming language)

Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
JavaScript
JavaScript

JavaScript is a scripting language widely used for client-side web development. It was the originating Programming language dialect of the ECMAScript standard....
OCaml
PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
Perl
Perl

In computer programming, Perl is a high-level programming language, List of programming languages by category, Interpreter , dynamic programming language....
Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
REBOL
REBOL

REBOL, the Relative Expression Based Object Language , is a data exchange language and programming languageREBOL Technologies, ....
Ruby
Ruby (programming language)

Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
Visual Basic .NET
Visual Basic .NET

Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework....
 
Windows PowerShell
Windows PowerShell

Windows PowerShell is an extensible command line interface shell and associated scripting language from Microsoft. It was released in 2006 and is currently available for Windows XP SP2/SP3, Windows Server 2003, Windows Vista and is included in Windows Server 2008 as well as Windows 7 as an optional feature....
 
  1. while (true) does not count as an infinite loop for this purpose, because it is not a dedicated language structure.
  2. C's for (init; condition; loop) loop is a general loop construct, not specifically a counting one, although it is often used for that.
  3. Deep breaks may be accomplished in C, C++ and C# through the use of labels and gotos.
  4. Iteration over objects was in PHP 5.
  5. A counting loop can be simulated by iterating over an incrementing list or generator, for instance, Python's range.
  6. Deep breaks may be accomplished through the use of exception handling.


Structured non-local control flow


Many programming languages, particularly those which favor 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. Exceptions
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
, condition
Condition

Condition can refer to:* A state of being.* Living condition, see Quality of life.* In health, a disease, such as a heart condition, as in Medical condition....
s
, and continuation
Continuation

In computing and programming, a continuation is an abstract representation of Control flow, or the "rest of computation" or "rest of code to be executed"....
s
are three common sorts of non-local control constructs.

Conditions


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

Exceptions


Modern languages have a structured construct for exception handling which does not rely on the use of GOTO:

try catch (someClass& someId) catch (someType& anotherId) catch (...)

Any number and variety of catch clauses can be used above. In 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 finally

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

using (FileStream stm = new FileStream ("logfile.txt", FileMode.Create))

Upon leaving the using-block, the compiler guarantees that the stm object is released. Python's with statement and Ruby's block argument to File.open are used to similar effect.

All these languages define standard exceptions and the circumstances under which they are thrown. Users can throw exceptions of their own (in fact C++ and Python allow users to throw and catch almost any type).

If there is no catch matching a particular throw, then control percolates back through subroutine 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.

The AppleScript
AppleScript

AppleScript is a scripting language devised by Apple Inc., and built into Mac OS. More generally, "AppleScript" is the word used to designate the Mac OS scripting interface, which is meant to operate in parallel with the graphical user interface....
 scripting programming language provides several pieces of information to a "try" block:

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 idiot!"

end try

Continuations


Non-local control flow cross reference


Programming language
Programming language

A programming language is a machine-readable artificial language designed to express computations that can be performed by a machine, particularly a computer....
conditions exceptions
Ada
C
C (programming language)

C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
C++
C++

C++ is a general-purpose programming language. It is regarded as a middle-level language, as it comprises a combination of both high-level programming language and low-level programming language language features....
C#
D
Haskell
Haskell (programming language)

Haskell is a standardized, purely functional programming language with non-strict programming language, named after logician Haskell Curry. The goals of the language are described as:...
Java
Java (programming language)

Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
Objective C
PHP
PHP

PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in Standalone software Graphical user interface....
PL/1
Python
Python (programming language)

Python is a general-purpose high-level programming language. Its design philosophy emphasizes code readability. Python's core syntax and semantics are Minimalism , while the standard library is large and comprehensive....
REBOL
REBOL

REBOL, the Relative Expression Based Object Language , is a data exchange language and programming languageREBOL Technologies, ....
Ruby
Visual Basic .NET
Visual Basic .NET

Visual Basic , formerly called Visual Basic .NET , is an object-oriented programming computer language that can be viewed as an evolution of Microsoft Visual Basic implemented on the .NET Framework....
Windows PowerShell
Windows PowerShell

Windows PowerShell is an extensible command line interface shell and associated scripting language from Microsoft. It was released in 2006 and is currently available for Windows XP SP2/SP3, Windows Server 2003, Windows Vista and is included in Windows Server 2008 as well as Windows 7 as an optional feature....


Proposed control structures

In a spoof Datamation
Datamation

Datamation was a computer magazine published in the United States between 1957 and 1998. When first published it wasn't clear there would be a significant market for a computer magazine given how few computers there were....
 article in 1973, R. Lawrence Clark suggested that the GOTO statement could be replaced by the COMEFROM
COMEFROM

In computer programming, COMEFROM is an obscure control flow structure used in some programming languages, primarily as a joke.COMEFROM is roughly the opposite of GOTO in that it can take the execution state from any arbitrary point in code to a COMEFROM statement....
 statement, and provides some entertaining examples. This was actually implemented in the INTERCAL programming language, a language designed to make programs as obscure as possible.

In his 1974 article "Structured Programming with go to Statements", Donald Knuth
Donald Knuth

Donald Ervin Knuth is a renowned computer science and Emeritus of the Art of Computer Programming at Stanford University.Author of the seminal multi-volume work The Art of Computer Programming , Knuth has been called the "father" of the run-time analysis, contributing to the development of, and systematizing formal mathematical techn...
 identified two situations which were not covered by the control structures listed above, and gave examples of control structures which could handle these situations. Despite their utility, these constructions have not yet found their way into mainstream programming languages.

Loop with test in the middle


This was proposed by Dahl
Ole-Johan Dahl

Ole-Johan Dahl was a Norway computer scientist and is considered to be one of the fathers of Simula and object-oriented programming along with Kristen Nygaard....
 in 1972.

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

If xxx1 is omitted we get a loop with the test at the top. If xxx2 is omitted we get a loop with the test at the bottom. If while is omitted we get an infinite loop. Hence this single construction can replace several constructions in most programming languages. A possible variant is to allow more than one while test; within the loop, but the use of exitwhen (see next section) appears to cover this case better.

As the example on the right shows (copying a file one character at a time), there are simple situations where this is exactly the right construction to use in order to avoid duplicated code and/or repeated tests. In Ada, the above loop construct (loop-while-repeat) can be represented using a standard infinite loop (loop - end loop) that has an exit when clause in the middle (not to be confused with the exitwhen statement in the following section).

with Ada.Text_IO; with Ada.Integer_Text_IO;

procedure Print_Squares is X : Integer; begin Read_Data : loop Ada.Integer_Text_IO.Get(X); exit Read_Data when X = 0; Ada.Text IO.Put (X * X); Ada.Text IO.New_Line; end loop Read_Data; end Print_Squares;

Naming a loop (Like Read_Data in our example) is optional but allows to leave the outer loop of several nested loops.

Multiple early exit/exit from nested loops

This was proposed by Zahn in 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
Exception handling

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
, 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

  • Branch (computer science)
    Branch (computer science)

    A branch is a point in a computer program where the flow of control is altered. The term branch is usually used when referring to a program written in machine code or assembly language; in a high-level programming language, branches usually take the form of conditional statements, subroutine calls or GOTO statements....
  • Control flow diagram
    Control flow diagram

    File:Performance seeking control flow diagram.jpgControl flow diagram is a diagram to describe the control flow of a business process, process or program....
  • Control flow graph
    Control flow graph

    File:Simplified Control Flowgraphs.jpgA control flow graph in computer science is a Group representation, using graph notation, of all paths that might be traversed through a computer program during its execution ....
  • Coroutine
    Coroutine

    In computer science, coroutines are program components that generalize subroutines to allow multiple entry points for suspending and resuming of execution at certain locations....
  • Cyclomatic complexity
    Cyclomatic complexity

    Cyclomatic complexity is a software metric . It was developed by Thomas J. McCabe in 1976 and is used to measure the complexity of a program. It directly measures the number of linearly independent paths through a program's source code....
  • Flowchart
    Flowchart

    A flowchart is common type of chart, that represents an algorithm or Process , showing the steps as boxes of various kinds, and their order by connecting these with arrows....
  • GOTO
    GOTO

    GOTO is a statement found in many computer programming languages. It is a combination of the English words wiktionary:go and wiktionary:to....
  • Main loop
  • Recursion
    Recursion

    Recursion, in mathematics and computer science, is a method of defining Function in which the function being defined is applied within its own definition....
  • Spaghetti code
    Spaghetti code

    Spaghetti code is a pejorative term for source code which has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" Branch constructs....
  • Structured programming
    Structured programming

    Structured programming can be seen as a subset or subdiscipline of procedural programming, one of the major programming paradigms. It is most famous for removing or reducing reliance on the GOTO Statement ....
  • Subroutine
    Subroutine

    In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....


External links