FACTOID # 108: Japan leads the world in car production, producing almost 50% more cars than either of its next closest competitors, Germany and the United StatesInteresting industry facts »
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Control flow

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 functional program are executed or evaluated. Within an imperative programming language, a control flow statement is an instruction that when executed can cause a change in the subsequent control flow to differ from the natural sequential order in which the instructions are listed. For non-strict functional languages, functions and language constructs exist to achieve the same ends, but they are not necessarily called control flow statements. Computer science, or computing science, is the study of the theoretical foundations of information and computation and their implementation and application in computer systems. ... A statement is the minimal unit of structuring in imperative programming languages. ... In computer science, an instruction typically refers to a single operation of a processor within a computer architecture. ... In computer science, a subroutine (function, procedure, or subprogram) is a sequence of code which performs a specific task, as part of a larger program, and is grouped as one or more statement blocks; such code is sometimes collected into software libraries. ... In computer science, imperative programming, as opposed to declarative programming, is a programming paradigm that describes computation in terms of a program state and statements that change the program state. ... Functional programming is a programming paradigm that conceives computation as the evaluation of mathematical functions and avoids state and mutable data. ... A computer program is a collection of instructions that describe a task, or set of tasks, to be carried out by a computer. ... A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... A strict programming language is one in which only strict functions may be defined by the user. ...


The kinds of control flow statements available differ by language, but can be roughly categorized by their effect:

  • continuation at a different statement (jump),
  • executing a set of statements only if some condition is met (choice),
  • executing a set of statements zero or more times, until some condition is met (loop),
  • executing a set of distant statements, after which the flow of control may possibly return (subroutines, coroutines, and continuations),
  • stopping the program, preventing any further execution (halt).

Interrupts and signals are low-level mechanisms that can alter the flow of control in a way similar to a subroutine, but are usually in response to some external stimulus or event rather than a control flow statement in the language. 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[citation needed]). In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ... In computer science, coroutines are program components that generalize subroutines to allow multiple entry points and suspending and resuming of execution at certain locations. ... In computing, a continuation is a representation of some of the execution state of a program (often the call stack and the current Instruction pointer) at a certain point. ... In computing, an interrupt is an asynchronous signal from hardware or software indicating the need for attention. ... A signal is a limited form of inter-process communication used in Unix, Unix-like, and other POSIX-compliant operating systems. ... In computer science, self-modifying code is code that alters its own instructions, whether or not it is on purpose, while it is executing. ... In computer science, a function is said to produce a side effect if it modifies some state other than its return value. ... This article does not cite any references or sources. ...


At the level of machine or assembly language, control flow instructions usually work by altering the program counter. For many[citation needed] CPUs the only control flow instructions available are conditional or unconditional branches (sometimes called jumps). Some processor designs also complicate the control flow by wavering from a strict sequential ordering of instructions, with features such as speculative execution, out-of-order execution, and branch delay slots. Compilers for higher-level programming languages must therefore translate all the many control-flow statements of the language into equivalent code using only the more limited instructions, and in a manner which preserves an observable behavior of a natural sequential flow - assuming that only one thread is executing. Discussion of control flow is almost always restricted to a single thread of execution, as it depends upon a definite sequence in which instructions are executed one at a time. A system of codes directly understandable by a computers CPU is termed this CPUs native or machine language. ... See the terminology section, below, regarding inconsistent use of the terms assembly and assembler. ... The program counter (also called the instruction pointer in some computers) is a register in a computer processor which indicates where the computer is in its instruction sequence. ... Die of an Intel 80486DX2 microprocessor (actual size: 12×6. ... In computer science, speculative execution is the execution of code whose result may not actually be needed. ... In computer engineering, out-of-order execution, OoOE, is a paradigm used in most high-performance microprocessors in order to make use of cycles that would otherwise be wasted by a certain type of costly delay. ... In computer architecture, a branch delay instruction is an instruction immediately following a conditional branch instruction which is executed whether or not the branch is taken. ... A diagram of the operation of a typical multi-language, multi-target compiler. ... For the form of code consisting entirely of subroutine calls, see Threaded code. ...

Contents

Primitives

Labels

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. Other than marking a position within the source code a label has no effect. Source code (commonly just source or code) is any series of statements written in some human-readable computer programming language. ...


Line numbers are a kind of label used in some languages (e.g. Fortran and BASIC), which are whole numbers placed at the beginning of each line of text within the source code. Languages which use line numbers often impose the constraint that the line numbers must increase in value in each subsequent line, but may not require that they be consecutive. For example, in BASIC: In computing, a line number is a way of specifying a point in a file by enumerating each line in the file by a number. ... Fortran (previously FORTRAN[1]) is a general-purpose[2], procedural,[3] imperative programming language that is especially suited to numeric computation and scientific computing. ... BASIC (Beginners All-purpose Symbolic Instruction Code) is a family of high-level programming languages. ... The whole numbers are the nonnegative integers (0, 1, 2, 3, ...) The set of all whole numbers is represented by the symbol = {0, 1, 2, 3, ...} Algebraically, the elements of form a commutative monoid under addition (with identity element zero), and under multiplication (with identity element one). ...

 10 X = 3 20 PRINT X 

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: C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... Identifiers (IDs) are lexical tokens that name entities. ...

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

The Algol 60 language allowed both whole numbers and identifiers as labels (both attached by colons to the following statement), but few if any other variants of Algol allowed whole numbers. ALGOL (short for ALGOrithmic Language) is a programming language originally developed in the mid 1950s which became the de facto standard way to report algorithms in print for almost the next 30 years. ...


Goto

Main article: GOTO

The goto statement (a juxtaposition of the English words go and to, and pronounced[citation needed] as two words) is the most basic form of unconditional transfer of control. GOTO is a statement found in many computer programming languages. ...


Although the keyword may either be in upper or lower case depending on the language, it is usually written as: In computer science, a keyword is an identifier which indicates a specific command. ...

 goto label 

The effect of a goto statement is to cause the next statement to be executed to always be the statement appearing immediately after (or at) the indicated label.


Goto statements have been considered harmful by many computer scientists, notably Dijkstra. In computer science and related disciplines, considered harmful is a phrase popularly used in the titles of diatribes and other critical essays. ... Portrait of Edsger Dijkstra (courtesy Brian Randell) Edsger Wybe Dijkstra (Rotterdam, May 11, 1930 – Nuenen, August 6, 2002) was a Dutch computer scientist. ...


Subroutines

Main article: 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 computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ... In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ... In object-oriented programming, a class consists of encapsulated instance variables and subprograms, the methods mentioned below. ... The type system of the Haskell programming language includes a construct called the type class that provides a powerful form of restricted parametric polymorphism. ...


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


Nowadays, subroutines are more frequently used to help make a program more structured, e.g. by isolating some particular algorithm or hiding some particular data access method. If many programmers are working on a single program, subroutines are one kind of modularity that can help split up the work. Modularity is a concept that has applications in the contexts of computer science, particularly programming, as well as cognitive science in investigating the structure of mind. ...


Minimal structured control flow

(See also Structured program theorem.) 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 structured program theorem is a result in programming language theory. ...


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)[citation needed], 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.) A strict programming language is one in which only strict functions may be defined by the user. ... In computer science, software transactional memory (STM) is a concurrency control mechanism analogous to database transactions for controlling access to shared memory in concurrent computing. ...


Control structures in practice

Wikibooks
Wikibooks Computer programming has a page on the topic of
Control

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. Image File history File links Wikibooks-logo-en. ... Wikibooks logo Wikibooks, previously called Wikimedia Free Textbook Project and Wikimedia-Textbooks, is a wiki for the creation of books. ...

  • No final keyword: Algol 60, C, C++, Haskell, Java, Pascal, Perl, PHP, PL/I, Python. Such languages need some way of grouping statements together:
    • Algol 60 and Pascal : begin ... end
    • C, C++, Java, Perl, and PHP: curly brackets { ... }
    • PL/1: DO ... END
    • Python: uses indentation level (see Off-side rule)
    • Haskell: either indentation level or curly brackets can be used, and they can be freely mixed
  • Final keyword: Ada, Algol 68, Modula-2, Fortran 77, Visual Basic. The forms of the final keyword vary:
    • Ada: final keyword is end + space + initial keyword e.g. if ... end if, loop ... end loop
    • Algol 68: initial keyword spelled backwards e.g. if ... fi, case ... esac
    • Fortran 77: final keyword is end + initial keyword e.g. IF ... ENDIF, DO ... ENDDO
    • Modula-2: same final keyword end for everything
    • Visual Basic: every control structure has its own keyword. If ... End If; For ... Next; Do ... Loop

ALGOL (short for ALGOrithmic Language) is a programming language originally developed in the mid 1950s which became the de facto standard way to report algorithms in print for almost the next 30 years. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, programming language with high-level and low-level capabilities. ... Haskell is a standardized purely functional programming language with non-strict semantics, named after the logician Haskell Curry. ... Java is a programming language originally developed by Sun Microsystems and released in 1995. ... Pascal is an imperative computer programming language, developed in 1970 by Niklaus Wirth as a language particularly suitable for structured programming. ... Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ... PHP is a reflective programming language originally designed for producing dynamic web pages. ... PL/I (Programming Language One, pronounced pee el one) is a computer programming language designed for scientific, engineering, and business applications. ... Python is a high-level programming language first released by Guido van Rossum in 1991. ... A computer programming language is said to adhere to the off-side rule if in it the scope of declarations (a statement block) is expressed by their indentation, i. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... ALGOL 68 (short for ALGOrithmic Language 1968) is an imperative computer 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 a more rigorously defined syntax and semantics. ... Modula-2 is a computer programming language invented by Niklaus Wirth at ETH around 1978, as a successor to Modula, an intermediate language by him. ... Fortran (previously FORTRAN[1]) is a general-purpose[2], procedural,[3] imperative programming language that is especially suited to numeric computation and scientific computing. ... Visual Basic (VB) is an event driven programming language and associated development environment from Microsoft for its COM programming model. ...

Choice

“Then” redirects here. ...

Loops

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


In some languages, such as Scheme, loops are often expressed using tail recursion rather than explicit looping constructs. Scheme is a multi-paradigm programming language. ... In computer science, tail recursion is a special case of recursion that can be easily transformed into an 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 body is skipped completely. 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 } 

See also For loop, Loop counter. It has been suggested that Foreach be merged into this article or section. ... A loop counter is a counting variable used in the loop structure of most computer programming languages. ...


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

 for X := 0.1 step 0.1 to 1.0 do

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


Condition-controlled loops

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

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

See also While loop. In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. ...


Collection-controlled loops

A few programming languages (e.g. Smalltalk, Perl, Java, C#, Visual Basic) have special constructs which allow you to implicitly loop through all elements of an array, or all members of a set or collection. For other uses, see Small talk. ... Wikibooks has a book on the topic of Perl Programming Perl is a dynamic programming language created by Larry Wall and first released in 1987. ... Java is a programming language originally developed by Sun Microsystems and released in 1995. ... The title given to this article is incorrect due to technical limitations. ... Visual Basic (VB) is an event driven programming language and associated development environment from Microsoft for its COM programming model. ...

 someCollection do: [:eachElement |xxx]. foreach someArray { xxx } Collection<String> coll; for (String s : coll) {} foreach (string s in myStringCollection) { xxx } 

General iteration

General iteration constructs such as C's for statement and Common Lisp's do form can be used to express any of the above sorts of loops, 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. Common Lisp, commonly abbreviated CL, is a dialect of the Lisp programming language, standardised by ANSI X3. ...


Infinite loops

Sometimes it is desirable for a program to loop forever, or until an exceptional condition such as an error arises. For instance, an event-driven program may be intended to loop forever handling events as they occur, only stopping when the process is killed by the operator. An infinite loop is a sequence of instructions in a computer program which loops endlessly, either due to the loop having no terminating condition or having one that can never be met. ...


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


Continuation with next iteration

Sometimes within the body of a loop there is a desire to skip the remainder of the loop body and continue with the next iteration of the loop. Some languages provide a statement such as continue or skip 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.


Early exit from loops

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


The following example is done in Ada which supports both Early exit from loops and Loop with test in the middle. Both features are very similar and comparing both code snipletts 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. Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... In computer science control flow (or alternatively, flow of control) refers to the order in which the individual statements or instructions of an imperative program are performed or executed. ... In computer science control flow (or alternatively, flow of control) refers to the order in which the individual statements or instructions of an imperative program are performed or executed. ...

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

Python supports conditional execution of code depending on whether a loop was exited early or not. For example, Python is a high-level programming language first released by Guido van Rossum in 1991. ...

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

Both Python's for and while loops support such an else clause, which is executed only if early exit of the loop did not occur.


Loop system cross reference table

Programming language conditional loop early exit continuation
begin middle end count collection general infinite [1]
Ada Yes Yes Yes Yes arrays No Yes deep nested No
C Yes No Yes No [2] No Yes No deep nested [3] Yes
C++ Yes No Yes No [2] No Yes No deep nested [3] Yes
FORTRAN Yes No No Yes No No Yes one level Yes
PHP Yes No Yes No [2] Yes [4] Yes No deep nested Yes
Python Yes No No No [5] Yes No No deep nested [6] Yes
  1. a  while (true) does not count as an infinite loop for this purpose, because it is not a dedicated language structure.
  2. a b c  C's for (init; condition; loop) loop is a general loop construct, not specifically a counting one, although it is often used for that.
  3. a  b  Deep breaks may be accomplished in C and C++ through the use of labels and gotos.
  4. a  Iteration over objects was added in PHP 5.
  5. a  A counting loop can be simulated by iterating over an incrementing list or generator, like range or xrange.
  6. a  Deep breaks may be accomplished in Python through the use of exception handling.

A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, programming language with high-level and low-level capabilities. ... Fortran (previously FORTRAN[1]) is a general-purpose[2], procedural,[3] imperative programming language that is especially suited to numeric computation and scientific computing. ... PHP is a reflective programming language originally designed for producing dynamic web pages. ... Python is a high-level programming language first released by Guido van Rossum in 1991. ...

Structured non-local control flow

Many programming languages, particularly those which favor more dynamic styles of programming, offer constructs for non-local control flow. These cause the flow of execution to jump out of a given context and resume at some predeclared point. Exceptions, conditions, and continuations are three common sorts of non-local control constructs. Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ... This is a disambiguation page &#8212; a navigational aid which lists other pages that might otherwise share the same title. ... In computing, a continuation is a representation of some of the execution state of a program (often the call stack and the current Instruction pointer) at a certain point. ...


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. PL/I (Programming Language One, pronounced pee el one) is a computer programming language designed for scientific, engineering, and business applications. ...


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

Main article: Exception handling

Modern languages have a structured construct for exception handling which does not rely on the use of GOTO: Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of some condition that changes the normal flow of execution. ...

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

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

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

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

Upon leaving the using-block, the compiler guarantees that the stm object is released.


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


If there is no catch matching a particular throw, then control percolates back through subroutine calls and/or nested blocks until a matching catch is found or until the end of the main program is reached, at which point the program is forcibly stopped with a suitable error message.


The AppleScript scripting programming language provides several pieces of information to a "try" block: AppleScript is a scripting language devised by Apple, Inc. ... Scripting programming languages (commonly called scripting languages or script languages) are computer programming languages designed for scripting the operation of a computer. ...

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

Continuations

Main article: Continuation

In computing, a continuation is a representation of some of the execution state of a program (often the call stack and the current Instruction pointer) at a certain point. ...

Non-local control flow cross reference

Programming language conditions exceptions
Ada No Yes
C No No
C++ No Yes
C# No Yes
D No Yes
Haskell No Yes
Java No Yes
Objective C No Yes
PHP No Yes
PL/1 Yes No
Python No Yes
Ruby No Yes

A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, programming language with high-level and low-level capabilities. ... The title given to this article is incorrect due to technical limitations. ... D is an object-oriented, imperative system programming language designed by Walter Bright of Digital Mars as a re-engineering of C/C++. He has done this by re-designing many C++ features, and borrowing ideas from other programming languages. ... Haskell is a standardized purely functional programming language with non-strict semantics, named after the logician Haskell Curry. ... Java is a programming language originally developed by Sun Microsystems and released in 1995. ... Objective-C, often referred to as ObjC or more seldomly as Objective C or Obj-C, is an object oriented programming language implemented as an extension to C. It is used primarily on Mac OS X and GNUstep, two environments based on the OpenStep standard, and is the primary language... PHP is a reflective programming language originally designed for producing dynamic web pages. ... PL/I (Programming Language One, pronounced pee el one) is a computer programming language designed for scientific, engineering, and business applications. ... Python is a high-level programming language first released by Guido van Rossum in 1991. ... Ruby is a reflective, object-oriented programming language. ...

Proposed control structures

In a spoof Datamation article (December 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 the INTERCAL programming language, a language designed to make programs as obscure as possible. Datamation was a computer magazine published in the United States between 1957 and 1997. ... In computer programming, COMEFROM is a control flow structure used in some programming languages. ... INTERCAL is a programming language parody, the canonical esoteric programming 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 main-stream programming languages. Donald Ervin Knuth ( or Ka-NOOTH[1], Chinese: [2]) (b. ...


Loop with test in the middle

This was proposed by Dahl in 1972. Professor emeritus Ole-Johan Dahl (October 12, 1931 – June 29, 2002) was a Norwegian computer scientist and is considered to be one of the fathers of Simula and object-oriented programming along with Kristen Nygaard. ...

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

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


As the example on the right shows (copying a file one character at a time), there are simple situations where this is exactly the right construction to use in order to avoid duplicated code and/or repeated tests.

Wikibooks
Wikibooks Ada Programming has a page on the topic of

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). Image File history File links Wikibooks-logo-en. ... Wikibooks logo Wikibooks, previously called Wikimedia Free Textbook Project and Wikimedia-Textbooks, is a wiki for the creation of books. ... Ada is a structured, statically typed imperative computer programming language designed by a team led by Jean Ichbiah of CII Honeywell Bull during 1977–1983. ...

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

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


Multiple early exit/exit from nested loops

This was proposed by Zahn in 1974. A modified version is presented here.

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

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


exitwhen is conceptually similar to the try/catch construct in C++, but is likely to be much more efficient since there is no percolation across subroutine calls and no transfer of arbitrary values. Also, the compiler can check that all specified events do actually occur and have associated actions.


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

Flow-driven programming is a computer programming paradigm used by traditional programs, which follow their own control flow pattern, only sometimes changing course at branch points. ... A branch (or jump on some computer architectures, such as the PDP-8 and Intel x86) is a point in a computer program where the flow of control is altered. ... A control flow graph (CFG) is a representation, using graph notation, of all paths that might be traversed through a program during its execution. ... In computer science, coroutines are program components that generalize subroutines to allow multiple entry points and suspending and resuming of execution at certain locations. ... A simple flowchart for what to do if a lamp doesnt work A flowchart (also spelled flow-chart and flow chart) is a schematic representation of an algorithm or a process. ... GOTO is a statement found in many computer programming languages. ... In computing, the main loop (sometimes called the event loop or main event loop) is a common design approach, typically used by applications featuring an event driven graphical user interface. ... A visual form of recursion known as the Droste effect. ... Spaghetti code is a pejorative term for source code which has a complex and tangled control structure, especially one using many GOTOs, exceptions, threads, or other unstructured branching constructs. ... Structured programming can be seen as a subset or subdiscipline of procedural programming, one of the major programming paradigms. ... In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ...

References

  • Dahl & Dijkstra & Hoare, "Structured Programming" Academic Press, 1972.
  • Knuth, Donald E. "Structured Programming with go to Statements" ACM Computing Surveys 6(4):261-301, December 1974.
  • Böhm, Jacopini. Flow diagrams, "Turing Machines and Languages with only Two Formation Rules" Comm. ACM, 9(5):366-371, May 1966.
  • Hoare, C. A. R. "Partition: Algorithm 63," "Quicksort: Algorithm 64," and "Find: Algorithm 65." Comm. ACM 4, 321-322, 1961.
  • Zahn, C. T. "A control statement for natural top-down structured programming" presented at Symposium on Programming Languages, Paris, 1974.

Communications of the ACM (CACM) is the flagship monthly magazine of the Association for Computing Machinery (ACM). ...

External links

  • Java Control Statements
  • Go To Statement Considered Harmful
  • A Linguistic Contribution of GOTO-less Programming
  • Structured Programming with Go To StatementsPDF (2.88 MiB)
  • IBM 704 ManualPDF (31.4 MiB)

  Results from FactBites:
 
Control Flow [EA User Guide] (188 words)
The Control Flow is a connector linking two nodes in an Activity diagram.
Control Flow connectors bridge the flow between Activity nodes, by directing the flow to the target node once the source node's activity is completed.
Each flow should have a Guard condition that is exclusive of the other and defines which edge is taken under what conditions.
  More results at FactBites »


 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments
Please enter the 5-letter protection code

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.