In
computer science
Computer science is the study of computation, automation, and information. Computer science spans theoretical disciplines (such as algorithms, theory of computation, information theory, and automation) to practical disciplines (includin ...
, control flow (or flow of control) is the order in which individual
statements
Statement or statements may refer to: Common uses
* Statement (computer science), the smallest standalone element of an imperative programming language
*Statement (logic), declarative sentence that is either true or false
*Statement, a declarativ ...
,
instructions or
function call
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions may ...
s of an
imperative program are
executed
Capital punishment, also known as the death penalty, is the State (polity), state-sanctioned practice of deliberately killing a person as a punishment for an actual or supposed crime, usually following an authorized, rule-governed process to ...
or evaluated. The emphasis on explicit control flow distinguishes an ''
imperative programming
In computer science, imperative programming is a programming paradigm of software that uses statements that change a program's state. In much the same way that the imperative mood in natural languages expresses commands, an imperative program co ...
'' language from a ''
declarative programming
In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.
Many languages that a ...
'' language.
Within an imperative
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
, a ''control flow statement'' is a statement that results in a choice being made as to which of two or more paths to follow. For
non-strict functional languages, functions and
language construct
In computer programming, a language construct is a syntactically allowable part of a program that may be formed from one or more lexical tokens in accordance with the rules of the programming language.
The term "language construct" is often use ...
s exist to achieve the same result, but they are usually not termed control flow statements.
A set of statements is in turn generally structured as a
block
Block or blocked may refer to:
Arts, entertainment and media Broadcasting
* Block programming, the result of a programming strategy in broadcasting
* W242BX, a radio station licensed to Greenville, South Carolina, United States known as ''96.3 ...
, which in addition to grouping, also defines a
lexical scope
In computer programming, the scope of a name binding (an association of a name to an entity, such as a variable) is the part of a program where the name binding is valid; that is, where the name can be used to refer to the entity. In other part ...
.
Interrupt
In digital computers, an interrupt (sometimes referred to as a trap) is a request for the processor to ''interrupt'' currently executing code (when permitted), so that the event can be processed in a timely manner. If the request is accepted ...
s and
signals are low-level mechanisms that can alter the flow of control in a way similar to a
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions ma ...
, but usually occur as a response to some external stimulus or event (that can occur
asynchronously
Asynchrony is the state of not being in synchronization.
Asynchrony or asynchronous may refer to:
Electronics and computing
* Asynchrony (computer programming), the occurrence of events independent of the main program flow, and ways to deal wit ...
), rather than execution of an ''in-line'' control flow statement.
At the level of
machine language
In computer programming, machine code is any low-level programming language, consisting of machine language instructions, which are used to control a computer's central processing unit (CPU). Each instruction causes the CPU to perform a ver ...
or
assembly language, control flow instructions usually work by altering the
program counter
The program counter (PC), commonly called the instruction pointer (IP) in Intel x86 and Itanium microprocessors, and sometimes called the instruction address register (IAR), the instruction counter, or just part of the instruction sequencer, is ...
. For some
central processing unit
A central processing unit (CPU), also called a central processor, main processor or just processor, is the electronic circuitry that executes instructions comprising a computer program. The CPU performs basic arithmetic, logic, controlling, an ...
s (CPUs), the only control flow instructions available are conditional or unconditional
branch
A branch, sometimes called a ramus in botany, is a woody structural member connected to the central trunk of a tree (or sometimes a shrub). Large branches are known as boughs and small branches are known as twigs. The term '' twig'' usually ...
instructions, also termed jumps.
Categories

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
A branch, sometimes called a ramus in botany, is a woody structural member connected to the central trunk of a tree (or sometimes a shrub). Large branches are known as boughs and small branches are known as twigs. The term '' twig'' usually ...
or jump)
* Executing a set of statements only if some condition is met (choice - i.e.,
conditional branch
A branch is an instruction in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order. ''Branch'' (or ''branching'', ''branc ...
)
* Executing a set of statements zero or more times, until some condition is met (i.e., loop - the same as
conditional branch
A branch is an instruction in a computer program that can cause a computer to begin executing a different instruction sequence and thus deviate from its default behavior of executing instructions in order. ''Branch'' (or ''branching'', ''branc ...
)
* Executing a set of distant statements, after which the flow of control usually returns (
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions ma ...
s,
coroutine
Coroutines are computer program components that generalize subroutines for non-preemptive multitasking, by allowing execution to be suspended and resumed. Coroutines are well-suited for implementing familiar program components such as cooperative ...
s, and
continuation
In computer science, a continuation is an abstract representation of the control state of a computer program. A continuation implements ( reifies) the program control state, i.e. the continuation is a data structure that represents the computat ...
s)
* Stopping the program, preventing any further execution (unconditional halt)
Primitives
Labels
A
label
A label (as distinct from signage) is a piece of paper, plastic film, cloth, metal, or other material affixed to a container or product, on which is written or printed information or symbols about the product or item. Information printed d ...
is an explicit name or number assigned to a fixed position within the
source code
In computing, source code, or simply code, is any collection of code, with or without comment (computer programming), comments, written using a human-readable programming language, usually as plain text. The source code of a Computer program, p ...
, and which may be referenced by control flow statements appearing elsewhere in the source code. A label marks a position within source code and has no other effect.
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 increm ...
s are an alternative to a named label used in some languages (such as
BASIC
BASIC (Beginners' All-purpose Symbolic Instruction Code) is a family of general-purpose, high-level programming languages designed for ease of use. The original version was created by John G. Kemeny and Thomas E. Kurtz at Dartmouth College ...
). They are
whole numbers placed at the start of each line of text in the source code. Languages which use these often impose the constraint that the line numbers must increase in value in each following 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 and
Ada, a label is an
identifier
An identifier is a name that identifies (that is, labels the identity of) either a unique object or a unique ''class'' of objects, where the "object" or class may be an idea, physical countable object (or class thereof), or physical noncountable ...
, usually appearing at the start of a line and immediately followed by a colon. For example, in C:
Success: printf("The operation was successful.\n");
The language
ALGOL 60
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
allowed both whole numbers and identifiers as labels (both linked by colons to the following statement), but few if any other
ALGOL
ALGOL (; short for "Algorithmic Language") is a family of imperative computer programming languages originally developed in 1958. ALGOL heavily influenced many other languages and was the standard method for algorithm description used by th ...
variants allowed whole numbers. Early
Fortran compilers only allowed whole numbers as labels. Beginning with Fortran-90, alphanumeric labels have also been allowed.
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
GoTo (goto, GOTO, GO TO or other case combinations, depending on the programming language) is a statement found in many computer programming languages. It performs a one-way transfer of control to another line of code; in contrast a function ca ...
by many computer scientists, notably
Dijkstra.
Subroutines
The terminology for
subroutine
In computer programming, a function or subroutine is a sequence of program instructions that performs a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed.
Functions ma ...
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
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. Such a constraint typically involves a type class T a ...
es).
In the 1950s, computer memories were very small by current standards so subroutines were used mainly to reduce program size. A piece of code was written once and then used many times from various other places in a program.
Today, subroutines are more often used to help make a program more structured, e.g., by isolating some algorithm or hiding some data access method. If many programmers are working on one program, subroutines are one kind of
modularity
Broadly speaking, modularity is the degree to which a system's components may be separated and recombined, often with the benefit of flexibility and variety in use. The concept of modularity is used primarily to reduce complexity by breaking a s ...
that can help divide the work.
Sequence
In structured programming, the ordered sequencing of successive commands is considered one of the basic control structures, which is used as a building block for programs alongside iteration, recursion and choice.
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 showed that choice can be replaced by loops (and yet more Boolean variables).
That such minimalism is possible does not mean that it is necessarily desirable; after all, computers theoretically need only
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, mainly 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 strategy, making components of programs even more freely composable.)
Some academics took a purist approach to the Böhm–Jacopini result and argued that even instructions like
break
and
return
from the middle of loops are bad practice as they are not needed in the Böhm–Jacopini proof, and thus they advocated that all loops should have a single exit point. This purist approach is embodied in the language
Pascal (designed in 1968–1969), which up to the mid-1990s was the preferred tool for teaching introductory programming in academia.
[Roberts, E. 995�]
Loop Exits and Structured Programming: Reopening the Debate
” ACM SIGCSE Bulletin, (27)1: 268–272. The direct application of the Böhm–Jacopini theorem may result in additional local variables being introduced in the structured chart, and may also result in some
code duplication In computer programming, duplicate code is a sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity. Duplicate code is generally considered undesirable for a nu ...
.
Pascal is affected by both of these problems and according to empirical studies cited by
Eric S. Roberts
Eric S. Roberts is an American computer scientist noted for his contributions to computer science education through textbook authorship and his leadership in computing curriculum development. He is a co-chair of the ACM Education Council, form ...
, student programmers had difficulty formulating correct solutions in Pascal for several simple problems, including writing a function for searching an element in an array. A 1980 study by Henry Shapiro cited by Roberts found that using only the Pascal-provided control structures, the correct solution was given by only 20% of the subjects, while no subject wrote incorrect code for this problem if allowed to write a return from the middle of a loop.
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
ALGOL 60 (short for ''Algorithmic Language 1960'') is a member of the ALGOL family of computer programming languages. It followed on from ALGOL 58 which had introduced code blocks and the begin and end pairs for delimiting them, representing a k ...
,
C,
C++,
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
,
Java
Java (; id, Jawa, ; jv, ꦗꦮ; su, ) is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea to the north. With a population of 151.6 million people, Java is the world's mo ...
,
Pascal,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
,
PHP
PHP is a General-purpose programming language, general-purpose scripting language geared toward web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementati ...
,
PL/I
PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language developed and published by IBM. It is designed for scientific, engineering, business and system programming. It ...
,
Python,
PowerShell
PowerShell is a task automation and configuration management program from Microsoft, consisting of a command-line shell and the associated scripting language. Initially a Windows component only, known as Windows PowerShell, it was made open-sou ...
. 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/I:
DO
...
END
** Python: uses
indent level (see
Off-side rule
A computer programming language is said to adhere to the off-side rule of syntax if blocks in that language are expressed by their indentation. The term was coined by Peter Landin, possibly as a pun on the offside rule in association footba ...
)
** Haskell: either
indent level or curly brackets can be used, and they can be freely mixed
** Lua: uses
do
...
end
* Final keyword:
Ada,
ALGOL 68
ALGOL 68 (short for ''Algorithmic Language 1968'') is an imperative 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 ...
,
Modula-2
Modula-2 is a structured, procedural programming language developed between 1977 and 1985/8 by Niklaus Wirth at ETH Zurich. It was created as the language for the operating system and application software of the Lilith personal workstation. It w ...
,
Fortran 77,
Mythryl,
Visual Basic Visual Basic is a name for a family of programming languages from Microsoft. It may refer to:
* Visual Basic .NET (now simply referred to as "Visual Basic"), the current version of Visual Basic launched in 2002 which runs on .NET
* Visual Basic (c ...
. 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
Choice
If-then-(else) statements
Conditional expressions and conditional constructs are features of a
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
which perform different computations or actions depending on whether a programmer-specified
boolean ''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 terminal
ENDIF
, others do not.
C 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
and
IF
to be combined into
ELSEIF
, avoiding the need to have a series of
ENDIF
or other final statements at the end of a compound statement.
Less common variations include:
* Some languages, such as
Fortran, have a ''three-way'' or ''
arithmetic if'', testing whether a numeric value is positive, negative or zero.
*Some languages have a
functional
Functional may refer to:
* Movements in architecture:
** Functionalism (architecture)
** Form follows function
* Functional group, combination of atoms within molecules
* Medical conditions without currently visible organic basis:
** Functional s ...
form of an
if
statement, for instance
Lisp's cond
.
*Some languages have an
operator
Operator may refer to:
Mathematics
* A symbol indicating a mathematical operation
* Logical operator or logical connective in mathematical logic
* Operator (mathematics), mapping that acts on elements of a space to produce elements of another ...
form of an
if
statement, such as C's
ternary operator
In mathematics, a ternary operation is an ''n''- ary operation with ''n'' = 3. A ternary operation on a set ''A'' takes any given three elements of ''A'' and combines them to form a single element of ''A''.
In computer science, a ternary operato ...
.
*
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
supplements a C-style
if
with
when
and
unless
.
*
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by ...
uses
ifTrue
and
ifFalse
messages to implement conditionals, rather than any fundamental language construct.
Case and switch statements
Switch statement
In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.
Switch statements function som ...
s (or ''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
In computer science, a lookup table (LUT) is an array that replaces runtime computation with a simpler array indexing operation. The process is termed as "direct addressing" and LUTs differ from hash tables in a way that, to retrieve a value v w ...
s. In
dynamic languages, the cases may not be limited to constant expressions, and might extend to
pattern matching
In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. In contrast to pattern recognition, the match usually has to be exact: "either it will or will not be ...
, as in the
shell script
A shell script is a computer program designed to be run by a Unix shell, a command-line interpreter. The various dialects of shell scripts are considered to be scripting languages. Typical operations performed by shell scripts include file manip ...
example on the right, where the
*)
implements the default case as a
glob matching any string. Case logic
can also be implemented in functional form, as in
SQL's
decode
statement.
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
Indefinite may refer to:
* the opposite of definite in grammar
** indefinite article
** indefinite pronoun
* Indefinite integral, another name for the antiderivative
* Indefinite forms in algebra, see definite quadratic forms
* an indefinite m ...
.
In
functional programming
In computer science, functional programming is a programming paradigm where programs are constructed by applying and composing functions. It is a declarative programming paradigm in which function definitions are trees of expressions that ...
languages, such as
Haskell
Haskell () is a general-purpose, statically-typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research and industrial applications, Haskell has pioneered a number of programming lan ...
and
Scheme A scheme is a systematic plan for the implementation of a certain idea.
Scheme or schemer may refer to:
Arts and entertainment
* ''The Scheme'' (TV series), a BBC Scotland documentary series
* The Scheme (band), an English pop band
* ''The Schem ...
, both
recursive
Recursion (adjective: ''recursive'') occurs when a thing is defined in terms of itself or of its type. Recursion is used in a variety of disciplines ranging from linguistics to logic. The most common application of recursion is in mathemati ...
and
iterative
Iteration is the repetition of a process in order to generate a (possibly unbounded) sequence of outcomes. Each repetition of the process is a single iteration, and the outcome of each iteration is then the starting point of the next iteration. ...
processes are expressed with
tail recursive procedures instead of looping constructs that are syntactic.
Count-controlled loops
Most programming languages have constructions for repeating a loop a certain number of times.
In most cases counting can go downwards instead of upwards and step sizes other than 1 can be used.
FOR I = 1 TO N , for I := 1 to N do begin
xxx , xxx
NEXT I , end;
------------------------------------------------------------
DO I = 1,N , for ( I=1; I<=N; ++I )
In these examples, if N < 1 then the body of loop may execute once (with I having value 1) or not at all, depending on the programming language.
In many programming languages, only integers can be reliably used in a count-controlled loop. Floating-point numbers are represented imprecisely due to hardware constraints, so a loop such as
for X := 0.1 step 0.1 to 1.0 do
might be repeated 9 or 10 times, depending on rounding errors and/or the hardware and/or the compiler version. Furthermore, if the increment of X occurs by repeated addition, accumulated rounding errors may mean that the value of X in each iteration can differ quite significantly from the expected sequence 0.1, 0.2, 0.3, ..., 1.0.
Condition-controlled loops