Control flow
Encyclopedia
In computer science
, control flow (or alternatively, flow of control) refers to the order in which the individual statements, instructions, or function calls of an imperative
or a declarative
program
are executed
or evaluated.
Within an imperative programming language
, a control flow statement is a statement whose execution results in a choice being made as to which of two or more paths should be followed. For non-strict
functional languages, functions and language constructs exist to achieve the same result, 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
s and signals
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 (that can occur asynchronous
ly), rather than execution of an 'in-line' control flow statement. Self-modifying code
can also be used to affect control flow through its side effects
, but usually does not involve an explicit control flow statement (an exception being the ALTER verb in COBOL
).
At the level of machine or assembly language
, control flow instructions usually work by altering the program counter
. For some CPUs
the only control flow instructions available are conditional or unconditional branch instruction
s (also called jumps).
is an explicit name or number assigned to a fixed position within the source code
, 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
s are an alternative to a named label (and used in some languages such as Fortran
and BASIC), that are whole numbers
placed at the beginning of each line of text within the source code. Languages which use these 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:
In other languages such as C
and Ada a label is an identifier
, usually appearing at the beginning of a line and immediately followed by a colon. For example, in C:
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.
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 be the statement appearing at (or immediately after) the indicated label.
Goto statements have been considered harmful
by many computer scientists, notably Dijkstra.
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
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 that is 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
that can help split up the work.
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
(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
- have continued this line of thought, making components of programs even more freely composable.)
which perform different computations or actions depending on whether a programmer-specified boolean
condition evaluates to true or false.
Less common variations include:-
s (in some languages, case statements or multiway branches) compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action ('else','otherwise') to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup table
s. 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
matching any string. Case logic
can also be implemented in functional form, as in SQL
's
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, or indefinitely
.
In functional programming
languages, such as Haskell
and Scheme, loops can be expressed by using recursion
or fixed point iteration
rather than explicit looping constructs. Tail recursion is a special case of recursion which can be easily transformed to iteration.
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,N for ( I=1; I<=N; ++I ) {
xxx xxx
END DO }
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.
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 executed at least once.
DO WHILE (test) repeat
xxx xxx
LOOP until test;
while (test) { do
xxx xxx
} while (test);
, Perl
, Object Pascal
, Java
, C#, Mythryl, Visual Basic
, Ruby
, Python
, JavaScript
, Fortran 95 and later) 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].
for Item in Collection do begin xxx end;
foreach (item; myCollection) { xxx }
foreach someArray { xxx }
Collection coll; for (String s : coll) {}
foreach (string s in myStringCollection) { xxx }
$someCollection | ForEach-Object { $_ }
forall ( index = first:last:step... )
'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.
s 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.
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.
The following example is done in Ada which supports both early exit from loops and loops with test in the middle. 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.
Python
supports conditional execution of code depending on whether a loop was exited early (with a
Note that the
s and loop invariants
are used to express correctness of loops.
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
.
, and continuation
s are three common sorts of non-local control constructs.
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
Any number and variety of
Since this pattern is fairly common, C# has a special syntax:
Upon leaving the
All these languages define standard exceptions and the circumstances under which they are thrown.
Users can throw exceptions of their own (in fact C++ allows users to throw and catch almost any type).
If there is no
The AppleScript
scripting programming language provides several pieces of information to a "
article in 1973, R. Lawrence Clark suggested that the GOTO statement could be replaced by the COMEFROM
statement, and provides some entertaining examples.
This was actually implemented in INTERCAL
, a deliberately esoteric programming language
language.
In his 1974 article "Structured Programming with go to Statements", Donald Knuth
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.
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.
Languages lacking this construct generally emulate it using an equivalent infinite-loop-with-break idiom:
while (true) {
xxx1
if (not test)
break
xxx2
}
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).
Naming a loop (like Read_Data in this example) is optional but permits leaving the outer loop of several nested loops.
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;
Computer science
Computer science or computing 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, instructions, or function calls of an imperative
Imperative programming
In computer science, imperative programming is a programming paradigm that describes computation in terms of statements that change a program state...
or a declarative
Declarative programming
In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow. Many languages applying this style attempt to minimize or eliminate side effects by describing what the program should accomplish, rather than...
program
Computer program
A computer program is a sequence of instructions written to perform a specified task with a computer. A computer requires programs to function, typically executing the program's instructions in a central processor. The program has an executable form that the computer can use directly to execute...
are executed
Execution (computers)
Execution in computer and software engineering is the process by which a computer or a virtual machine carries out the instructions of a computer program. The instructions in the program trigger sequences of simple actions on the executing machine...
or evaluated.
Within an imperative programming language
Programming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
, a control flow statement is a statement whose execution results in a choice being made as to which of two or more paths 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 allows the user to define non-strict functions, and hence may allow lazy evaluation.- Examples :Nearly all programming languages in common use today are strict...
functional languages, functions and language constructs exist to achieve the same result, 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 (unconditional branch or jumpBranch (computer science)A branch is sequence of code in a computer program which is conditionally executed depending on whether the flow of control is altered or not . The term can be used when referring to programs in high level languages as well as program written in machine code or assembly language...
), - executing a set of statements only if some condition is met (choice - i.e. conditional branch),
- executing a set of statements zero or more times, until some condition is met (i.e. loop - the same as conditional branch),
- executing a set of distant statements, after which the flow of control usually returns (subroutineSubroutineIn computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
s, coroutineCoroutineCoroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations...
s, and continuationContinuationIn computer science and programming, a continuation is an abstract representation of the control state of a computer program. A continuation reifies the program control state, i.e...
s), - stopping the program, preventing any further execution (unconditional halt).
Interrupt
Interrupt
In computing, an interrupt is an asynchronous signal 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. When a signal is sent to a process, the operating system...
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 (that can occur asynchronous
Asynchronous systems
In a synchronous system, operations are coordinated under thecentralized control of a fixed-rate clock signal or several clocks. Anasynchronous digital system, in contrast, has no global clock: instead,...
ly), rather than execution of an 'in-line' control flow statement. Self-modifying code
Self-modifying code
In computer science, self-modifying code is code that alters its own instructions while it is executing - usually to reduce the instruction path length and improve performance or simply to reduce otherwise repetitively similar code, thus simplifying maintenance...
can also be used to affect control flow through its side effects
Side effect (computer science)
In computer science, a function or expression is said to have a side effect if, in addition to returning a value, it also modifies some state or has an observable interaction with calling functions or the outside world...
, 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. 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 programming language for computers, microprocessors, microcontrollers, and other programmable devices. It implements a symbolic representation of the machine codes and other constants needed to program a given CPU architecture...
, control flow instructions usually work by altering the program counter
Program counter
The program counter , commonly called the instruction pointer in Intel x86 microprocessors, and sometimes called the instruction address register, or just part of the instruction sequencer in some computers, is a processor register that indicates where the computer is in its instruction sequence...
. For some CPUs
Central processing unit
The central processing unit is the portion of a computer system that carries out the instructions of a computer program, to perform the basic arithmetical, logical, and input/output operations of the system. The CPU plays a role somewhat analogous to the brain in the computer. The term has been in...
the only control flow instructions available are conditional or unconditional branch instruction
Branch (computer science)
A branch is sequence of code in a computer program which is conditionally executed depending on whether the flow of control is altered or not . The term can be used when referring to programs in high level languages as well as program written in machine code or assembly language...
s (also called jumps).
Labels
A labelLabel (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 character . In many high level programming languages the purpose of a label is to act as the...
is an explicit name or number assigned to a fixed position within the source code
Source code
In computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...
, 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.In the C...
s are an alternative to a named label (and used in some languages such as Fortran
Fortran
Fortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
and BASIC), that are whole numbers
Natural number
In mathematics, the natural numbers are the ordinary whole numbers used for counting and ordering . These purposes are related to the linguistic notions of cardinal and ordinal numbers, respectively...
placed at the beginning of each line of text within the source code. Languages which use these 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:
In other languages such as C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and Ada a label is an identifier
Identifier
An identifier is a name that identifies either a unique object or a unique class of objects, where the "object" or class may be an idea, physical [countable] object , or physical [noncountable] substance...
, usually appearing at the beginning of a line and immediately followed by a colon. For example, in C:
The Algol 60
ALGOL 60
ALGOL 60 is a member of the ALGOL family of computer programming languages. It gave rise to many other programming languages, including BCPL, B, Pascal, Simula, C, and many others. ALGOL 58 introduced code blocks and the begin and end pairs for delimiting them...
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 be the statement appearing at (or immediately after) 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 subroutineSubroutine
In computer science, a subroutine is a portion of code within a larger program that 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 ad-hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic 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 that is 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 of separate, interchangeable components called modules by breaking down program functions into modules, each of which accomplishes one function and contains everything necessary to accomplish...
that can help split up the work.
Minimal structured control flow
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 , sometimes called an ultimate reduced instruction set computer , is an abstract machine that uses only one instruction – obviating the need for a machine language opcode...
(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. It is an alternative to lock-based synchronization. A transaction in this context is a piece of code that...
- 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, CC (programming language)C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
, C++C++C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
, HaskellHaskell (programming language)Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
, JavaJava (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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, Pascal, PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, PHPPHPPHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document...
, PL/I, PythonPython (programming language)Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, PowerShellWindows PowerShellWindows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework...
. Such languages need some way of grouping statements together:- Algol 60 and Pascal :
begin
...end
- C, C++, Java, Perl, PHP, and PowerShell: curly brackets
{
...}
- PL/1:
DO
...END
- Python: uses indentation level (see Off-side ruleOff-side ruleA computer programming language is said to adhere to the off-side rule if the scope of declarations in that language is expressed by their indentation. The term and the idea are attributed to Peter J. Landin, and the term can be seen as a pun on the offside law of football .- Definition :Peter J...
) - Haskell: either indentation level or curly brackets can be used, and they can be freely mixed
- Algol 60 and Pascal :
- Final keyword: Ada, Algol 68ALGOL 68ALGOL 68 isan imperative computerprogramming language that was conceived as a successor to theALGOL 60 programming language, designed with the goal of a...
, Modula-2Modula-2Modula-2 is a computer programming language designed and developed between 1977 and 1980 by Niklaus Wirth at ETH Zurich as a revision of Pascal to serve as the sole programming language for the operating system and application software for the personal workstation Lilith...
, Fortran 77FortranFortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
, Mythryl, Visual BasicVisual BasicVisual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM 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, Mythryl: 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
;While
...Wend
- Ada: final keyword is
If-then-(else) statements
Conditional expressions and conditional constructs are features of a programming languageProgramming language
A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely....
which perform different computations or actions depending on whether a programmer-specified boolean
Boolean datatype
In computer science, the Boolean or logical data type is a data type, having two values , intended to represent the truth values of logic and Boolean algebra...
condition evaluates to true or false.
-
IF..GOTO
. A form found in unstructured languages, mimicking a typical machine code instruction, would jump to (GOTO) a label or line number when the condition was met. -
IF..THEN..(ENDIF)
. Rather than being restricted to a jump, any simple statement, or nested block, could follow the THEN key keyword This a structured form. -
IF..THEN..ELSE..(ENDIF)
. As above, but with a second action to be performed if the condition is false. This is one of the most common forms, with many variations. Some require a terminalENDIF
, others do not. CCĈ or ĉ is a consonant in Esperanto orthography, representing the sound .Esperanto orthography uses a diacritic for all four of its postalveolar consonants, as do the Latin-based Slavic alphabets...
and related languages do not require a terminal keyword, or a 'then', but do require parentheses around the condition. - Conditional statements can be and often are nested inside other conditional statements. Some languages allow
ELSE
andIF
to be combined intoELSEIF
, avoiding the need to have a series ofENDIF
or other final statements at the end of a compound statement.
Pascal Pascal (programming language) Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal... : |
C C (programming language) C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.... : |
Shell script Shell script A shell script is a script written for the shell, or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language... : |
Python Python (programming language) Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive... : |
---|---|---|---|
Less common variations include:-
- Some languages, such as FortranFortranFortran is a general-purpose, procedural, imperative programming language that is especially suited to numeric computation and scientific computing...
, have a "three-way" or "arithmetic ifArithmetic IFThe arithmetic IF statement has been for several decades a three-way arithmetic conditional statement, starting from the very early version of Fortran, and including FORTRAN IV, FORTRAN 66 and FORTRAN 77...
", testing whether a numeric value is positive, negative or zero. - Some languages have a functionalFunctional analysisFunctional analysis is a branch of mathematical analysis, the core of which is formed by the study of vector spaces endowed with some kind of limit-related structure and the linear operators acting upon these spaces and respecting these structures in a suitable sense...
form of an "if" statement, for instance LISPLispA lisp is a speech impediment, historically also known as sigmatism. Stereotypically, people with a lisp are unable to pronounce sibilants , and replace them with interdentals , though there are actually several kinds of lisp...
's. - Some languages have an operatorOperator (programming)Programming languages typically support a set of operators: operations which differ from the language's functions in calling syntax and/or argument passing mode. Common examples that differ by syntax are mathematical arithmetic operations, e.g...
form of an "if" statement, such as C's ternary operator. - PerlPerlPerl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
supplements a C-styleif
withwhen
andunless
. - SmalltalkSmalltalkSmalltalk is an object-oriented, dynamically typed, reflective 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...
usesifTrue
andifFalse
messages to implement conditionals, rather than any fundamental language construct.
Case and switch statements
Switch statementSwitch statement
In computer programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programming languages such as Pascal, Ada, C/C++, C#, Java, and so on. It is also included in several other types of languages...
s (in some languages, case statements or multiway branches) compare a given value with specified constants and take action according to the first constant to match. There is usually a provision for a default action ('else','otherwise') to be taken if no match succeeds. Switch statements can allow compiler optimizations, such as lookup table
Lookup table
In computer science, a lookup table is a data structure, usually an array or associative array, often used to replace a runtime computation with a simpler array indexing operation. The savings in terms of processing time can be significant, since retrieving a value from memory is often faster than...
s. In dynamic languages, the cases may not be limited to constant expressions, and might extend to pattern matching
Pattern matching
In computer science, pattern matching is the act of checking some sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact. The patterns generally have the form of either sequences or tree structures...
, as in the shell script
Shell script
A shell script is a script written for the shell, or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language...
example on the right, where the
'*)'
implements the default case as a regular expressionRegular expression
In computing, a regular expression provides a concise and flexible means for "matching" strings of text, such as particular characters, words, or patterns of characters. Abbreviations for "regular expression" include "regex" and "regexp"...
matching any string. Case logic
can also be implemented in functional form, as in SQL
SQL
SQL is a programming language designed for managing data in relational database management systems ....
's
decode
statement. Pascal Pascal (programming language) Pascal is an influential imperative and procedural programming language, designed in 1968/9 and published in 1970 by Niklaus Wirth as a small and efficient language intended to encourage good programming practices using structured programming and data structuring.A derivative known as Object Pascal... : |
C C (programming language) C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.... : |
Shell script Shell script A shell script is a script written for the shell, or command line interpreter, of an operating system. It is often considered a simple domain-specific programming language... : |
---|---|---|
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, or indefinitely
Infinite loop
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over...
.
In functional programming
Functional programming
In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data. It emphasizes the application of functions, in contrast to the imperative programming style, which emphasizes changes in state...
languages, such as Haskell
Haskell (programming language)
Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the...
and Scheme, loops can be expressed by using recursion
Recursion (computer science)
Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem. The approach can be applied to many types of problems, and is one of the central ideas of computer science....
or fixed point iteration
Fixed point combinator
In computer science, a fixed-point combinator is a higher-order function that computes a fixed point of other functions. A fixed point of a function f is a value x such that x = f. For example, 0 and 1 are fixed points of the function f = x2, because 0 = 02 and 1 = 12...
rather than explicit looping constructs. Tail recursion is a special case of recursion which can be easily transformed to iteration.
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,N for ( I=1; I<=N; ++I ) {
xxx xxx
END DO }
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
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 executed at least once.
DO WHILE (test) repeat
xxx xxx
LOOP until test;
while (test) { do
xxx xxx
} while (test);
Collection-controlled loops
Several programming languages (e.g. Ada, D, SmalltalkSmalltalk
Smalltalk is an object-oriented, dynamically typed, reflective 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...
, Perl
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular...
, Object Pascal
Object Pascal
Object Pascal refers to a branch of object-oriented derivatives of Pascal, mostly known as the primary programming language of Embarcadero Delphi.-Early history at Apple:...
, 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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
, C#, Mythryl, Visual Basic
Visual Basic
Visual Basic is the third-generation event-driven programming language and integrated development environment from Microsoft for its COM programming model...
, Ruby
Ruby (programming language)
Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto...
, Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive...
, JavaScript
JavaScript
JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles....
, Fortran 95 and later) 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].
for Item in Collection do begin xxx end;
foreach (item; myCollection) { xxx }
foreach someArray { xxx }
Collection
foreach (string s in myStringCollection) { xxx }
$someCollection | ForEach-Object { $_ }
forall ( index = first:last:step... )
General iteration
General iteration constructs such as C's for statement and Common LispCommon Lisp
Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers...
'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 loops
Infinite loopInfinite loop
An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition, having one that can never be met, or one that causes the loop to start over...
s 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
Server (computing)
In the context of client-server architecture, a server is a computer program running to serve the requests of other programs, the "clients". Thus, the "server" performs some computational task on behalf of "clients"...
) should loop forever handling events as they occur, only stopping when the process is terminated by an operator.
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
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 ascontinue
(most languages), skip
, 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
Some languages, like Perl and Ruby, have aredo
statement that restarts the current iteration from the beginning.Restart loop
Ruby has aretry
statement that restarts the entire loop from the initial iteration.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 asbreak
(most languages), exit
, or last
(Perl), whose effect is to terminate the current loop immediately and transfer control to the statement immediately following that loop. One can also return
out of a subroutine executing the looped statements, breaking out of both the nested loop and the subroutine. Things can get a bit messy if searching a multi-dimensional table using nested loops (see #Proposed control structures below).The following example is done in Ada which supports both early exit from loops and loops with test in the middle. 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.
Python
Python (programming language)
Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its 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,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 has not occurred.Loop variants and invariants
Loop variantLoop variant
In computer science, a loop variant is a mathematical function defined on the state space of a computer program whose value is monotonically decreased with respect to a well-founded relation by the iteration of a while loop under some invariant conditions, thereby ensuring its termination...
s and loop invariants
Loop invariant
In computer science, a loop invariant is an invariant used to prove properties of loops. Informally, a loop invariant is a statement of the conditions that should be true on entry into a loop and that are guaranteed to remain true on every iteration of the loop...
are used to express correctness of loops.
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
Eiffel (programming language)
Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method...
contain native support for loop variants and invariants. In other cases, support is an add-on, such as the Java Modeling Language's
Java Modeling Language
The Java Modeling Language is a specification language for Java programs, using Hoare style pre- and postconditions and invariants, that follows the design by contract paradigm...
specification for loop statements in 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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
.
Loop system cross reference table
Programming language Programming language A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely.... |
conditional | loop | early exit | continuation | redo | retry | correctness facilities | ||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
begin | middle | end | count | collection | general | variant | invariant | ||||||
Ada | |||||||||||||
C C (programming language) C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.... |
|||||||||||||
C++ C++ C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell... |
|||||||||||||
C# | |||||||||||||
Common Lisp Common Lisp Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, published in ANSI standard document ANSI INCITS 226-1994 , . From the ANSI Common Lisp standard the Common Lisp HyperSpec has been derived for use with web browsers... |
|||||||||||||
Eiffel Eiffel (programming language) Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method... |
|||||||||||||
F# | |||||||||||||
FORTRAN 77 | |||||||||||||
Fortran 90 | |||||||||||||
Fortran 95 and later | |||||||||||||
Haskell Haskell (programming language) Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the... |
|||||||||||||
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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities... |
|||||||||||||
JavaScript JavaScript JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. It is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles.... |
|||||||||||||
OCaml | |||||||||||||
PHP PHP PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document... |
|||||||||||||
Perl Perl Perl is a high-level, general-purpose, interpreted, dynamic programming language. Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting language to make report processing easier. Since then, it has undergone many changes and revisions and become widely popular... |
|||||||||||||
Python Python (programming language) Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive... |
|||||||||||||
REBOL REBOL REBOL is a cross-platform data exchange language and a multi-paradigm dynamic programming language originally designed by Carl Sassenrath for network communications and distributed computing. The language and its official implementation, which is a proprietary freely redistributable software are... |
|||||||||||||
Ruby Ruby (programming language) Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto... |
|||||||||||||
Standard ML Standard ML Standard ML is a general-purpose, modular, functional programming language with compile-time type checking and type inference. It is popular among compiler writers and programming language researchers, as well as in the development of theorem provers.SML is a modern descendant of the ML... |
|||||||||||||
Visual Basic .NET Visual Basic .NET Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework... |
|||||||||||||
Windows PowerShell Windows PowerShell Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework... |
-
while (true)
does not count as an infinite loop for this purpose, because it is not a dedicated language structure. - C's
for (init; test; increment)
loop is a general loop construct, not specifically a counting one, although it is often used for that. - Deep breaks may be accomplished in C, C++ and C# through the use of labels and gotos.
- Iteration over objects was added in PHP 5.
- A counting loop can be simulated by iterating over an incrementing list or generator, for instance, Python's
range
. - Deep breaks may be accomplished through the use of exception handling.
- There is no special construct, since the
while
function can be used for this. - There is no special construct, but users can define general loop functions.
- The C++11 standard introduced the range-based for. In the STLStandard Template LibraryThe Standard Template Library is a C++ software library which later evolved into the C++ Standard Library. It provides four components called algorithms, containers, functors, and iterators. More specifically, the C++ Standard Library is based on the STL published by SGI. Both include some...
there is anstd::for_each
templateTemplate (programming)Templates are a feature of the C++ programming language that allow functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one....
function which can iterate on STL containersContainer (data structure)In computer science, a container is a class, a data structure, or an abstract data type whose instances are collections of other objects. In other words; they are used for storing objects in an organized way following specific access rules...
and call an unary functionUnary functionA unary function is a function that takes one argument. In computer science, a unary operator is a subset of unary function.Many of the elementary functions are unary functions, in particular the trigonometric functions and hyperbolic function are unary....
for each element. The functionality also can be constructed as macro on these containers. - Count controlled looping is effected by iteration across an integer interval; early exit by including an additional condition for exit.
- Eiffel supports a reserved word
retry
, however it is used in exception handling, not loop control. - Requires Java Modeling LanguageJava Modeling LanguageThe Java Modeling Language is a specification language for Java programs, using Hoare style pre- and postconditions and invariants, that follows the design by contract paradigm...
(JML) behavioral interface specification language. - Requires loop variants to be integers; transfinite variants are not supported. http://archive.eiffel.com/doc/faq/variant.html
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. Conditions, exceptionsException 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 program execution....
, and continuation
Continuation
In computer science and programming, a continuation is an abstract representation of the control state of a computer program. A continuation reifies the program control state, i.e...
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 ofGOTO
: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:Since this pattern is fairly common, C# has a special syntax:
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++ allows 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 created by Apple Inc. and built into Macintosh operating systems since System 7. The term "AppleScript" may refer to the scripting system itself, or to particular scripts that are written in the AppleScript language....
scripting programming language provides several pieces of information to a "
try
" block:Non-local control flow cross reference
Programming language Programming language A programming language is an artificial language designed to communicate instructions to a machine, particularly a computer. Programming languages can be used to create programs that control the behavior of a machine and/or to express algorithms precisely.... |
conditions | exceptions |
---|---|---|
Ada Ada (programming language) Ada is a structured, statically typed, imperative, wide-spectrum, and object-oriented high-level computer programming language, extended from Pascal and other languages... |
||
C C (programming language) C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system.... |
||
C++ C++ C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell... |
||
C# | ||
D D (programming language) The D programming language is an object-oriented, imperative, multi-paradigm, system programming language created by Walter Bright of Digital Mars. It originated as a re-engineering of C++, but even though it is mainly influenced by that language, it is not a variant of C++... |
||
Eiffel Eiffel (programming language) Eiffel is an ISO-standardized, object-oriented programming language designed by Bertrand Meyer and Eiffel Software. The design of the language is closely connected with the Eiffel programming method... |
||
Haskell Haskell (programming language) Haskell is a standardized, general-purpose purely functional programming language, with non-strict semantics and strong static typing. It is named after logician Haskell Curry. In Haskell, "a function is a first-class citizen" of the programming language. As a functional programming language, the... |
||
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 platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities... |
||
Mythryl | ||
Objective-C Objective-C Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.Today, it is used primarily on Apple's Mac OS X and iOS: two environments derived from the OpenStep standard, though not compliant with it... |
||
PHP PHP PHP is a general-purpose server-side scripting language originally designed for web development to produce dynamic web pages. For this purpose, PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor module, which generates the web page document... |
||
PL/I PL/I PL/I is a procedural, imperative computer programming language designed for scientific, engineering, business and systems programming applications... |
||
Python Python (programming language) Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. Python claims to "[combine] remarkable power with very clear syntax", and its standard library is large and comprehensive... |
||
REBOL REBOL REBOL is a cross-platform data exchange language and a multi-paradigm dynamic programming language originally designed by Carl Sassenrath for network communications and distributed computing. The language and its official implementation, which is a proprietary freely redistributable software are... |
||
Ruby Ruby (programming language) Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto... |
||
Visual Basic .NET Visual Basic .NET Visual Basic .NET , is an object-oriented computer programming language that can be viewed as an evolution of the classic Visual Basic , which is implemented on the .NET Framework... |
||
Windows PowerShell Windows PowerShell Windows PowerShell is Microsoft's task automation framework, consisting of a command-line shell and associated scripting language built on top of, and integrated with the .NET Framework... |
Proposed control structures
In a spoof DatamationDatamation
Datamation was a print 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, originally as a joke....
statement, and provides some entertaining examples.
This was actually implemented in INTERCAL
INTERCAL
INTERCAL, a programming language parody, is an esoteric programming language that was created by Don Woods and James M. Lyon, two Princeton University students, in 1972. It satirizes aspects of the various programming languages at the time, as well as the proliferation of proposed language...
, a deliberately esoteric programming language
Esoteric programming language
An esoteric programming language is a programming language designed as a test of the boundaries of computer programming language design, as a proof of concept, or as a joke...
language.
In his 1974 article "Structured Programming with go to Statements", Donald Knuth
Donald Knuth
Donald Ervin Knuth is a computer scientist and Professor Emeritus at Stanford University.He is the author of the seminal multi-volume work The Art of Computer Programming. Knuth has been called the "father" of the analysis of algorithms...
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
The following was proposed by DahlOle-Johan Dahl
Ole-Johan Dahl was a Norwegian computer scientist and is considered to be one of the fathers of Simula and object-oriented programming along with Kristen Nygaard.- Career :...
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.
Languages lacking this construct generally emulate it using an equivalent infinite-loop-with-break idiom:
while (true) {
xxx1
if (not test)
break
xxx2
}
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).
Naming a loop (like Read_Data in this example) is optional but permits leaving 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 program 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 sequence of code in a computer program which is conditionally executed depending on whether the flow of control is altered or not . The term can be used when referring to programs in high level languages as well as program written in machine code or assembly language...
- Control flow diagramControl flow diagramA control flow diagram is a diagram to describe the control flow of a business process, process or program.Control flow diagrams were developed in the 1950s, and are widely used in multiple engineering disciplines...
- Control flow graphControl flow graphA control flow graph in computer science is a representation, using graph notation, of all paths that might be traversed through a program during its execution.- Overview :...
- Control tableControl tableControl tables are tables that control the program flow or play a major part in program control. There are no rigid rules concerning the structure or content of a control table - its only qualifying attribute is its ability to direct program flow in some way through its 'execution' by an associated...
- CoroutineCoroutineCoroutines are computer program components that generalize subroutines to allow multiple entry points for suspending and resuming execution at certain locations...
- Cyclomatic complexityCyclomatic complexityCyclomatic complexity is a software metric . It was developed by Thomas J. McCabe, Sr. in 1976 and is used to indicate the complexity of a program. It directly measures the number of linearly independent paths through a program's source code...
- FlowchartFlowchartA flowchart is a type of diagram that represents an algorithm or process, showing the steps as boxes of various kinds, and their order by connecting these with arrows. This diagrammatic representation can give a step-by-step solution to a given problem. Process operations are represented in these...
- GOTOGotogoto is a statement found in many computer programming languages. It is a combination of the English words go and to. It performs a one-way transfer of control to another line of code; in contrast a function call normally returns control...
- Main loop
- RecursionRecursionRecursion is the process of repeating items in a self-similar way. For instance, when the surfaces of two mirrors are exactly parallel with each other the nested images that occur are a form of infinite recursion. The term has a variety of meanings specific to a variety of disciplines ranging from...
- Spaghetti codeSpaghetti codeSpaghetti code is a pejorative term for source code that has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other "unstructured" branching constructs. It is named such because program flow tends to look like a bowl of spaghetti, i.e. twisted and...
- Structured programmingStructured programmingStructured programming is a programming paradigm aimed on improving the clarity, quality, and development time of a computer program by making extensive use of subroutines, block structures and for and while loops - in contrast to using simple tests and jumps such as the goto statement which could...
- SubroutineSubroutineIn computer science, a subroutine is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code....
- Switch statementSwitch statementIn computer programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programming languages such as Pascal, Ada, C/C++, C#, Java, and so on. It is also included in several other types of languages...
, alters control flow conditionally