control flow not to be confused with flow control data in computer science control flow or flow of control is the order in which individual statements instructions or function calls of an imperative program are executed or evaluated the emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language within an imperative programming language a control flow statement is a statement the execution of which results in a choice being made as to which of two or more paths to follow for nonstrict functional languages functions and language constructs 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 which in addition to grouping also defines a lexical scope interrupts and signals are lowlevel 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 asynchronously rather than execution of an inline control flow statement at the level of machine language or assembly language control flow instructions usually work by altering the program counter for some central processing units cpus the only control flow instructions available are conditional or unconditional branch instructions also termed jumps categories a flow chart showing control flow 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 jump executing a set of statements only if some condition is met choice ie conditional branch executing a set of statements zero or more times until some condition is met ie loop the same as conditional branch executing a set of distant statements after which the flow of control usually returns subroutines coroutines and continuations stopping the program preventing any further execution unconditional halt primitives labels label computer science a label 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 a label marks a position within source code and has no other effect line numbers are an alternative to a named label and used in some languages such as basic that 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 usually appearing at the start of a line and immediately followed by a colon for example in c success printfthe operation was successfuln the language algol 60 allowed both whole numbers and identifiers as labels both linked by colons to the following statement but few if any other algol variants allowed whole numbers early fortran compilers only allowed whole numbers as labels beginning with fortran90 alphanumeric labels have also been allowed goto 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 by many computer scientists notably dijkstra subroutines subroutine the terminology for subroutines 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 classes 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 eg by isolating some algorithm or hiding some data access method if many programmers are working on one program subroutines are one kind of modularity that can help divide the work sequence structured programming 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 see also structured program theorem in may 1966 bhm and jacopini published an article in communications of the acm which showed that any program with gotos could be transformed into a gotofree form involving only choice if then else and loops while condition do xxx possibly with duplicated code andor the addition of boolean variables truefalse 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 bhm and jacopinis article showed was that all programs could be gotofree 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 nonstrict 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 bhmjacopini 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 bhmjacopini 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 19681969 which up to the mid1990s was the preferred tool for teaching introductory programming in academia control structures in practice most programming languages with control structures have an initial keyword which indicates the type of control structure involved languages then divide as to whether or not control structures have a final keyword no final keyword algol 60 c c haskell java pascal perl php pli python powershell such languages need some way of grouping statements together algol 60 and pascal begin end c c java perl php and powershell curly brackets pli do end python uses indent level see offside rule 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 modula2 fortran 77 mythryl visual basic the forms of the final keyword vary ada final keyword is end space initial keyword eg if end if loop end loop algol 68 mythryl initial keyword spelled backwards eg if fi case esac fortran 77 final keyword is end initial keyword eg if endif do enddo modula2 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 ifthenelse statements conditional programming conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmerspecified boolean condition evaluates to true or false ifgoto 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 ifthenendif rather than being restricted to a jump any simple statement or nested block could follow the then key keyword this a structured form ifthenelseendif 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 pascal ada c shell script python lisp if a 0 then writelnyes else writelnno if a 0 then putlineyes else putlineno end if if a 0 printfyes else printfno if then echo yes else echo no fi if a 0 printyes else printno princ if plusp a yes no less common variations include some languages such as fortran have a threeway or arithmetic if testing whether a numeric value is positive negative or zero some languages have a functional form of an if statement for instance lisps cond some languages have an operator form of an if statement such as cs ternary operator perl supplements a cstyle if with when and unless smalltalk uses iftrue and iffalse messages to implement conditionals rather than any fundamental language construct case and switch statements switch statement switch statements 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 tables in dynamic languages the cases may not be limited to constant expressions and might extend to pattern matching as in the shell script example on the right where the implements the default case as a glob matching any string case logic can also be implemented in functional form as in sqls decode statement pascal ada c shell script lisp case somechar of a actionona x actiononx yzactiononyandz else actiononnomatch end case somechar is when a actionona when x actiononx when y z actiononyandz when others actiononnomatch end switch somechar case a actionona break case x actiononx break case y case z actiononyandz break default actiononnomatch case somechar in a actionona x actiononx actiononyandz actiononnomatch esac case somechar a actionona x actiononx y z actiononyandz else actiononnomatch 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 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 countcontrolled loops for loop 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 1n for i1 in i xxx xxx end do 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 countcontrolled loop floatingpoint numbers are represented imprecisely due to hardware constraints so a loop such as for x 01 step 01 to 10 do might be repeated 9 or 10 times depending on rounding errors andor the hardware andor 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 01 02 03 10 conditioncontrolled loops while loop and do while loop most programming languages have constructions for repeating a loop until some condition changes some variations test the condition at the start of the loop others test it at the end if the test is at the start the body may be skipped completely if it is at the end the body is always executed at least once do while test repeat xxx xxx loop until test while test do xxx xxx while test a control break is a value change detection method used within ordinary loops to trigger processing for groups of values values are monitored within the loop and a change diverts program flow to the handling of the group event associated with them do until endoffile if newzipcode currentzipcode displaytallycurrentzipcode zipcount currentzipcode newzipcode zipcount 0 endif zipcount loop collectioncontrolled loops foreach several programming languages eg ada d c11 smalltalk php perl object pascal java c matlab visual basic ruby python javascript fortran 95 and later have special constructs which allow implicit looping through all elements of an array or all members of a set or collection somecollection do for item in collection do begin xxx end foreach item mycollection xxx foreach somearray xxx foreach somearray as k v xxx collectionstring coll for string s coll foreach string s in mystringcollection xxx somecollection foreachobject forall index firstlaststep scala has forexpressions which generalise collectioncontrolled loops and also support other uses such as asynchronous programming haskell has doexpressions and comprehensions which together provide similar function to forexpressions in scala general iteration general iteration constructs such as cs for statement and common lisps do form can be used to express any of the above sorts of loops and others such as looping over some number of collections in parallel where a more specific looping construct can be used it is usually preferred over the general iteration construct since it often makes the purpose of the expression clearer infinite loops infinite loop infinite loops are used to assure a program segment loops forever or until an exceptional condition arises such as an error for instance an eventdriven program such as a server should loop forever handling events as they occur only stopping when the process is terminated by an operator infinite loops can be implemented using other control flow constructs most commonly in unstructured programming this is jump back up goto while in structured programming this is an indefinite loop while loop set to never end either by omitting the condition or explicitly setting it to true as while true some languages have special constructs for infinite loops typically by omitting the condition from an indefinite loop examples include ada loop end loop fortran do end do go for and ruby loop do end often an infinite loop is unintentionally created by a programming error in a conditioncontrolled 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 as continue 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 a redo statement that restarts the current iteration from the start restart loop ruby has a retry statement that restarts the entire loop from the initial iteration early exit from loops when using a countcontrolled loop to search through a table it might be desirable to stop searching as soon as the required item is found some programming languages provide a statement such as break most languages exit visual basic or last perl which effect is to terminate the current loop immediately and transfer control to the statement immediately after that loop 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 must be combined with an if statement while a condition in the middle is a selfcontained construct with adatext io with adainteger text io procedure printsquares is x integer begin readdata loop adainteger text iogetx exit readdata when x 0 adatext ioput x x adatext ionewline end loop readdata end printsquares python supports conditional execution of code depending on whether a loop was exited early with a break statement or not by using an elseclause with the loop for example for n in setofnumbers if isprimen print set contains a prime number break else print set did not contain any prime numbers the else clause in the above example is linked to the for statement and not the inner if statement both pythons for and while loops support such an else clause which is executed only if early exit of the loop has not occurred some languages support breaking out of nested loops in theory circles these are called multilevel breaks one common use example is searching a multidimensional table this can be done either via multilevel breaks break out of n levels as in bash the notion of multilevel breaks is of some interest in theoretical computer science because it gives rise to what is today called the kosaraju hierarchy one can also return out of a subroutine executing the looped statements breaking out of both the nested loop and the subroutine there are other proposed control structures for multiple breaks but these are generally implemented as exceptions instead in his 2004 textbook david watt uses tennents notion of sequencer to explain the similarity between multilevel breaks and return statements watt notes that a class of sequencers known as escape sequencers defined as sequencer that terminates execution of a textually enclosing command or procedure encompasses both breaks from loops including multilevel breaks and return statements as commonly implemented however return sequencers may also carry a return value whereas the break sequencer as implemented in contemporary languages usually cannot loop variants and invariants loop variants and loop invariants are used to express correctness of loops in practical terms a loop variant is an integer expression which has an initial nonnegative value the variants 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 addon such as the java modeling languages specification for loop statements in java loop sublanguage some lisp dialects provide an extensive sublanguage for describing loops an early example can be found in conversional lisp of interlisp common lisp provides a loop macro which implements such a sublanguage loop system crossreference table programming language conditional loop early exit continuation redo retry correctness facilities begin middle end count collection general infinite variant invariant ada yes yes yes yes arrays no yes deep nested no c yes no yes no no yes no deep nested deep nested no c yes no yes no yes yes no deep nested deep nested no c yes no yes no yes yes no deep nested deep nested cobol yes no yes yes no yes no deep nested deep nested no common lisp yes yes yes yes builtin only yes yes deep nested no d yes no yes yes yes yes yes deep nested deep nested no eiffel yes no no yes yes yes no one level no no no integer only yes f yes no no yes yes no no no no no fortran 77 yes no no yes no no no one level yes fortran 90 yes no no yes no no yes deep nested yes fortran 95 and later yes no no yes arrays no yes deep nested yes haskell no no no no yes no yes no no no java yes no yes no yes yes no deep nested deep nested no nonnative nonnative javascript yes no yes no yes yes no deep nested deep nested no natural yes yes yes yes no yes yes yes yes yes no ocaml yes no no yes arrayslists no no no no no php yes no yes no yes yes no deep nested deep nested no perl yes no yes no yes yes no deep nested deep nested yes python yes no no no yes no no deep nested deep nested no rebol no yes yes yes yes no yes one level no no ruby yes no yes yes yes no yes deep nested deep nested yes yes standard ml yes no no no arrayslists no no no no no visual basic net yes no yes yes yes no yes one level per type of loop one level per type of loop powershell yes no yes no yes yes no yes a while true does not count as an infinite loop for this purpose because it is not a dedicated language structure a b c d e f g h cs for init test increment loop is a general loop construct not specifically a counting one although it is often used for that a b c deep breaks may be accomplished in c c and c through the use of labels and gotos a iteration over objects was added in php 5 a b c a counting loop can be simulated by iterating over an incrementing list or generator for instance pythons range a b c d e deep breaks may be accomplished through the use of exception handling a there is no special construct since the while function can be used for this a there is no special construct but users can define general loop functions a the c11 standard introduced the rangebased for in the stl there is a stdforeach template function which can iterate on stl containers and call a unary function for each element a countcontrolled looping is effected by iteration across an integer interval early exit by including an additional condition for exit a eiffel supports a reserved word retry however it is used in exception handling not loop control a requires java modeling language jml behavioral interface specification language a requires loop variants to be integers transfinite variants are not supported a d supports infinite collections and the ability to iterate over those collections this does not require any special construct a deep breaks can be achieved using go to and procedures a common lisp predates the concept of generic collection type structured nonlocal control flow many programming languages especially those favoring more dynamic styles of programming offer constructs for nonlocal control flow these cause the flow of execution to jump out of a given context and resume at some predeclared point conditions exceptions and continuations are three common sorts of nonlocal control constructs more exotic ones also exist such as generators coroutines and the async keyword conditions pli has some 22 standard conditions eg 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 exception handling modern languages have a specialized structured construct for exception handling which does not rely on the use of goto or multilevel breaks or returns for example in c one can write try xxx1 somewhere in here xxx2 use throw somevalue xxx3 catch someclass someid catch value of someclass actionforsomeclass catch sometype anotherid catch value of sometype actionforsometype catch catch anything not already caught actionforanythingelse any number and variety of catch clauses can be used above if there is no catch matching a particular throw control percolates back through subroutine calls andor nested blocks until a matching catch is found or until the end of the main program is reached at which point the program is forcibly stopped with a suitable error message via cs influence catch is the keyword reserved for declaring a patternmatching exception handler in other languages popular today like java or c some other languages like ada use the keyword exception to introduce an exception handler and then may even employ a different keyword when in ada for the pattern matching a few languages like applescript incorporate placeholders in the exception handler syntax to automatically extract several pieces of information when the exception occurs this approach is exemplified below by the on error construct from applescript try set mynumber to mynumber 0 on error e number n from f to t partial result pr if e cant divide by zero then display dialog you must not do that end try david watts 2004 textbook also analyzes exception handling in the framework of sequencers introduced in this article in the section on early exits from loops watt notes that an abnormal situation generally exemplified with arithmetic overflows or inputoutput failures like file not found is a kind of error that is detected in some lowlevel program unit but in object pascal d java c and python a finally clause can be added to the try construct no matter how control leaves the try the code inside the finally clause is guaranteed to execute this is useful when writing code that must relinquish an expensive resource such as an opened file or a database connection when finished processing filestream stm null c example try stm new filestream logfiletxt filemodecreate return processstuffstm may throw an exception finally if stm null stmclose since this pattern is fairly common c has a special syntax using filestream stm new filestream logfiletxt filemodecreate return processstuffstm may throw an exception upon leaving the usingblock the compiler guarantees that the stm object is released effectively binding the variable to the file stream while abstracting from the side effects of initializing and releasing the file pythons with statement and rubys block argument to fileopen are used to similar effect all the languages mentioned above define standard exceptions and the circumstances under which they are thrown users can throw exceptions of their own in fact c allows users to throw and catch almost any type including basic types like int whereas other languages like java arent as permissive continuations continuation async c 50 introduced the async keyword for supporting asynchronous io in a direct style generators generators also known as semicoroutines allow control to be yielded to a consumer method temporarily typically using a yield keyword like the async keyword this supports programming in a direct style coroutines coroutines are functions that can yield control to each other a form of cooperative multitasking without threads coroutines can be implemented as a library if the programming language provides either continuations or generators so the distinction between coroutines and generators in practice is a technical detail nonlocal control flow cross reference programming language conditions exceptions generatorscoroutines async ada no yes c no no no no c no yes yes by using boost c no yes yes yes cobol yes yes no no common lisp yes no d no yes yes eiffel no yes erlang no yes yes f no yes yes yes go no yes yes haskell no yes yes no java no yes no no javascript yes yes es6 yes stage 3 objectivec no yes no php no yes yes pli yes no no no python no yes yes rebol yes yes no ruby no yes yes scala no yes via experimental extension via experimental extension tcl via traces yes yes via event loop visual basic net yes yes no powershell no yes no proposed control structures in a spoof datamation article in 1973 r lawrence clark suggested that the goto statement could be replaced by the comefrom statement and provides some entertaining examples comefrom was implemented in one esoteric programming language named intercal donald knuths 1974 article structured programming with go to statements identifies 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 constructs have not yet found their way into mainstream programming languages loop with test in the middle the following was proposed by dahl in 1972 loop loop xxx1 readchar while test while not atendoffile xxx2 writechar repeat repeat if xxx1 is omitted we get a loop with the test at the top a traditional while loop if xxx2 is omitted we get a loop with the test at the bottom equivalent to a do while loop in many languages if while is omitted we get an infinite loop the construction here can be thought of as a do loop with the while check in the middle hence this single construction can replace several constructions in most programming languages languages lacking this construct generally emulate it using an equivalent infiniteloopwithbreak idiom while true xxx1 if not test break xxx2 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 in ada the above loop construct loopwhilerepeat can be represented using a standard infinite loop loop end loop that has an exit when clause in the middle not to be confused with the exitwhen statement in the following section with adatextio with adaintegertextio procedure printsquares is x integer begin readdata loop adaintegertextiogetx exit readdata when x 0 adatext ioput x x adatext ionewline end loop readdata end printsquares naming a loop like readdata in this example is optional but permits leaving the outer loop of several nested loops multiple early exitexit 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 and exceptions or similar constructs are used for this purpose in many languages the following simple example involves searching a twodimensional table for a particular item exitwhen found or missing for i 1 to n do for j 1 to m do if table target then found missing exits found print item is in table missing print item is not in table endexit security one way to attack a piece of software is to redirect the flow of execution of a program a variety of controlflow integrity techniques including stack canaries buffer overflow protection shadow stacks and vtable pointer verification are used to defend against these attacks branch computer science control flow analysis control flow diagram control flow graph control table coroutine cyclomatic complexity drakonchart flowchart goto jeroo helps learn control structures main loop recursion scheduling computing spaghetti code structured programming subroutine switch statement alters control flow conditionally hoare c a r partition algorithm 63 quicksort algorithm 64 and find algorithm 65 comm acm 4 321322 1961 the wikibook ada programming has a page on the topic of control the wikibook computer programming has a page on the topic of control media related to control flow at wikimedia commons go to statement considered harmful a linguistic contribution of gotoless programming structured programming with go to statements pdf archived from the original pdf on 20090824288mb ibm 704 manual pdf314mb 