Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Control flow

From Wikipedia, the free encyclopedia
(Redirected fromControl structure)
How software progresses through its implementation
Not to be confused withFlow control (data).
Loop constructs

Insoftware,control flow (orflow of control) describes howexecution progresses from onecommand to the next. In many contexts, such asmachine code and animperativeprogramming language, control progresses sequentially (to the command located immediately after the currently executing command) except when a command transfers control to another point – in which case the command is classified as a control flow command. Depending on context, other terms are used instead ofcommand. For example, in machine code, the typical term isinstruction and in an imperative language, the typical term isstatement.

Although an imperative language encodes control flow explicitly, languages of otherprogramming paradigms are less focused on control flow. Adeclarative language specifies desired results without prescribing an order of operations. Afunctional language uses bothlanguage constructs andfunctions to control flow even though they are usually not called control flow statements.

For acentral processing unit (CPU)instruction set, a control flow instruction often alters theprogram counter and is either an unconditionalbranch (a.k.a. jump) or a conditional branch. An alternative approach ispredication which conditionally enables instructions instead of branching.

Anasynchronous control flow transfer such as aninterrupt or asignal alters the normal flow of control to a hander before returning control to where it was interrupted.

One way to attack software is to redirect the flow of execution. A variety ofcontrol-flow integrity techniques, includingstack canaries,buffer overflow protection, shadow stacks, andvtable pointer verification, are used to defend against these attacks.[1][2][3]

Structure

[edit]

Control flow is closely related to code structure. Control flows along lines defined by structure and the execution rules of a language. This general concept of structure is not be confused withstructured programming which limits structure to sequencing, selection and iteration based onblock organization.

Sequence

[edit]

Sequential execution is the most basic structure. Although not all code is sequential in nature, imperative code is.

Label

[edit]

Alabel identifies a position insource code. Some control flow statements reference a label so that control jumps to the labeled line. Other than marking a position, a label has no other effect.

Some languages limit a label to a number which is sometimes called aline number although that implies the inherent index of the line; not a label. None-the-less, such numeric labels are typically required to increment from top to bottom in a file even if not be sequential. For example, in BASIC:

10LETX=320PRINTX30GOTO10

In many languages, a label is an alphanumericidentifier, usually appearing at the start of a line and immediately followed by a colon. For example, the following C code defines a labelSuccess on line 3 which identifies a jump target point at the first statement that follows it; line 4.

voidf(boolok){if(ok){gotosuccess;}return;success:printf("OK");}

Block

[edit]

Most languages provide for organizing sequences of code as ablock. When used with a control statement, the beginning of a block provides a jump target. For example, in the following C code (which uses curly braces to delimit a block), control jumps from line 1 to 4 if done is false.

if(done){printf("All done");}else{printf("Still workin' on it");}

Control

[edit]

Many control commands have been devised for programming languages. This section describes notable constructs; organized by functionality.

Function

[edit]

A function provides for control flow in that when called, execution jumps to the start of the function's code and when it completes, control returns the calling point. In the following C code, control jumps from line 6 to 2 in order to call functionfoo(). Then, after completing the function body (printing "Hi"), control returns to after the call, line 7.

voidfoo(){printf("Hi");}voidbar(){foo();printf("Done");}

Branch

[edit]

A branch command moves the point of execution from the point in the code that contains the command to the point that the command specifies.

Jump

[edit]

A jump command unconditionally branches control to another point in the code, and is the most basic form of controlling the flow of code.

In a high-level language, this is often provided as agoto statement. Although thekeyword may be upper or lower case or one or two words depending on the language, it is like:gotolabel. When control reaches a goto statement, control then jumps to the statement that follows the indicated label. The goto statement is beenconsidered harmful by many computer scientists; notablyDijkstra.

Conditional branch

[edit]

Aconditional statement jumps control based on the value of aBoolean expression. Common variations include:

if-goto
Jumps to a label based on a condition; a high-level programming statement that closely mimics a similar used machine code instruction
if-then
Rather than being restricted to a jump, a statement or block is executed if the expression is true. In a language that does not include thethen keyword, this can be called an if statement.
if-then-else
Like if-then, but with a second action to be performed if the condition is false. In a language that does not include thethen keyword, this can be called an if-else statement.
Nested
Conditional statements are often nested inside other conditional statements.
Arithmetic if
EarlyFortran, had anarithmetic if (a.k.a. three-way if) that tests whether a numeric value is negative, zero, or positive. This statement was deemed obsolete in Fortran-90, and deleted as of Fortran 2018.
Functional
Some languages have afunctional form; for instanceLisp'scond.
Operator
Some languages have anoperator form, such as theternary conditional operator.
When and unless
Perl supplements a C-styleif withwhen andunless.
Messages
Smalltalk usesifTrue andifFalse messages to implement conditionals, rather than a language construct.

The followingPascal code shows a simple if-then-else. The syntax is similar inAda:

ifa>0thenwriteln("yes")elsewriteln("no");

InC:

if(a>0){puts("yes");}else{puts("no");}

Inbash:

if[$a-gt0];thenecho"yes"elseecho"no"fi

InPython:

ifa>0:print("yes")else:print("no")

InLisp:

(princ(if(pluspa)"yes""no"))

Multiway branch

[edit]

A multiway branch jumps control based on matching values. There is usually a provision for a default action if no match is found. A switch statement can allow compiler optimizations, such aslookup tables. Indynamic languages, the cases may not be limited to constant expressions, and might extend topattern matching, as in theshell script example on the right, where the*) implements the default case as aglob matching any string. Case logic can also be implemented in functional form, as inSQL'sdecode statement.

The followingPascal code shows a relatively simpleswitch statement. Pascal uses thecase keyword instead ofswitch.

casesomeCharof'a':actionOnA;'x':actionOnX;'y','z':actionOnYandZ;elseactionOnNoMatch;end;

InAda:

casesomeChariswhen'a'=>actionOnA;when'x'=>actionOnX;when'y'|'z'=>actionOnYandZ;whenothers=>actionOnNoMatch;end;

InC:

switch(someChar){case'a':actionOnA;break;case'x':actionOnX;break;case'y':case'z':actionOnYandZ;break;default:actionOnNoMatch;}

InBash:

case$someCharina)actionOnA;;x)actionOnX;;[yz])actionOnYandZ;;*)actionOnNoMatch;;esac

InLisp:

(casesome-char((#\a)action-on-a)((#\x)action-on-x)((#\y#\z)action-on-y-and-z)(elseaction-on-no-match))

InFortran:

select case(someChar)case('a')actionOnAcase('x')actionOnXcase('y','z')actionOnYandZcasedefaultactionOnNoMatchend select

Loop

[edit]
basic types of program loops

A loop is a sequence of statements, loop body, which is executed a number of times based on runtime state. The body is executed once for each item of a collection (definite iteration), until a condition is met (indefinite iteration), orinfinitely. A loop inside the loop body is called anested loop.[4][5][6] Early exit from a loop may be supported via a break statement.[7][8]

In afunctional programming language, such asHaskell andScheme, bothrecursive anditerative processes are expressed withtail recursive procedures instead of looping constructs that are syntactic.

Numeric

[edit]
Main article:For loop

A relatively simple yet useful loop iterates over a range of numeric values. A simple form starts at an integer value, ends at a larger integer value and iterates for each integer value between. Often, the increment can be any integer value; even negative to loop from a larger to a smaller value.

Example in BASIC:

FORI=1TONxxxNEXTI

Example in Pascal:

forI:=1toNdobeginxxxend;

Example in Fortran:

DOI=1,NxxxEND DO

In many programming languages, only integers can be used at all or reliably. As a floating-point number is represented imprecisely due to hardware constraints, the following loop might iterate 9 or 10 times, depending on various factors such as rounding error, hardware, compiler. 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 commonly expected sequence of 0.1, 0.2, 0.3, ..., 1.0.

for X := 0.1step 0.1to 1.0do

Condition-controlled

[edit]
Main articles:While loop andDo while loop

Some loop constructs iterate until a condition is true. Some variations test the condition at the start of the loop; others test at the end. If the test is at the start, the body may be skipped completely. At the end, the body is always executed at least once.

Example in Visual Basic:

DOWHILE(test)xxxLOOP

Example in Pascal:

repeatxxxuntiltest;

Example in C family of pre-test:

while(test){xxx}

Example in C family of post-test:

doxxxwhile(test);

Although using thefor keyword, the 3-part, c-style loop is condition-based; not a numeric-based construct. The condition, 2nd part, is evaluated before each loop so the loop is pre-test. The 1st part is a place to initialize state and the 3rd part is for incrementing for the next iteration, but both aspects can be performed elsewhere. The following C code implements the logic of a numeric loop that iterates for i from 0 to n-1.

for(inti=0;i<n;++i){xxx}

Enumeration

[edit]
Main article:Foreach

Some loop constructs enumerate the items of a collection; iterating for each item.

Example in Smalltalk:

someCollectiondo: [:eachElement|xxx].

Example in Pascal:

forIteminCollectiondobeginxxxend;

Example in Raku:

foreach (item;myCollection) {xxx }

Example in TCL:

foreachsomeArray{xxx}

Example in PHP:

foreach($someArrayas$k=>$v){xxx}

Example in Java:

Collection<String>coll;for(Strings:coll){}

Example in C#:

foreach(stringsinmyStringCollection){xxx}

Example in PowerShell where 'foreach' is an alias of 'ForEach-Object':

someCollection|foreach{$_}

Example in Fortran:

forall(index=first:last:step...)

Scala hasfor-expressions, which generalise collection-controlled loops, and also support other uses, such asasynchronous programming.Haskell has do-expressions and comprehensions, which together provide similar function to for-expressions in Scala.

Infinite

[edit]
This section is an excerpt fromInfinite loop.[edit]
Loop constructs

Incomputer programming, aninfinite loop (or endless loop)[9][10] is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs, such as turning off power via a switch or pulling a plug. It may be intentional.

There is no general algorithm to determine whether a computer program contains an infinite loop or not; this is thehalting problem.

Loop-and-a-half problem

[edit]

Common loop structures sometimes result in duplicated code, either repeated statements or repeated conditions. This arises for various reasons and has various proposed solutions to eliminate or minimize code duplication.[11] Other than the traditional unstructured solution of agoto statement,[12] general structured solutions include having a conditional (if statement) inside the loop (possibly duplicating the condition but not the statements) or wrapping repeated logic in a function (so there is a duplicated function call, but the statements are not duplicated).[11]

A common case is where the start of the loop is always executed, but the end may be skipped on the last iteration.[12] This was dubbed by Dijkstra a loop which is performed "n and a half times",[13] and is now called theloop-and-a-half problem.[8] Common cases include reading data in the first part, checking for end of data, and then processing the data in the second part; or processing, checking for end, and then preparing for the next iteration.[12][8] In these cases, the first part of the loop is executedn{\displaystyle n} times, but the second part is only executedn1{\displaystyle n-1} times.

This problem has been recognized at least since 1967 by Knuth, with Wirth suggesting solving it via early loop exit.[14] Since the 1990s this has been the most commonly taught solution, using abreak statement, as in:[8]

loopstatementsifconditionbreakstatementsrepeat

A subtlety of this solution is that the condition is theopposite of a usualwhile condition: rewritingwhilecondition ...repeat with an exit in the middle requires reversing the condition:loop ...if notconditionexit ...repeat. Theloop with test in the middle control structure explicitly supports the loop-an-a-half use case, without reversing the condition.[14]

Unstructured

[edit]

A loop construct provides for structured completion criteria that either results in another iteration or continuing execution after the loop statement. But, various unstructured control flow constructs are supported by many languages.

Early next iteration
Some languages provide a construct that jumps control to the beginning of the loop body for the next iteration; for example,continue (most common),skip,[15]cycle (Fortran), ornext (Perl and Ruby).
Redo iteration
Some languages, like Perl[16] and Ruby,[17] have aredo statement that jumps to the start of the body for the same iteration.
Restart
Ruby has aretry statement that restarts the entire loop from the first iteration.[18]
Early exit
[edit]

Early exit jumps control to after the loop body[19][8] For example, when searching a list, can stop looping when the item is found. Some programming languages provide a statement such asbreak (most languages),Exit (Visual Basic), orlast (Perl).

In the following Ada code, the loop exits when X is 0.

loopGet(X);ifX=0thenexit;endif;DoSomething(X);endloop;

A more idiomatic style usesexit when:

loopGet(X);exitwhenX=0;DoSomething(X);endloop;

Python supports conditional execution of code depending on whether a loop was exited early (with abreak statement) or not by using an else-clause with the loop. In the following Python code, theelse clause is linked to thefor statement, and not the innerif statement. Both Python'sfor andwhile loops support such an else clause, which is executed only if early exit of the loop has not occurred.

forninset_of_numbers:ifisprime(n):print("Set contains a prime number")breakelse:print("Set did not contain any prime numbers")
Multi-level breaks
[edit]

Some languages support breaking out of nested loops; in theory circles, these are calledmulti-level breaks. One common use example is searching a multi-dimensional table. This can be done either via multilevel breaks (break out ofN levels), as in bash[20] and PHP,[21] or via labeled breaks (break out and continue at given label), as in Ada, Go, Java, Rust and Perl.[22] Alternatives to multilevel breaks include single breaks, together with a state variable which is tested to break out another level; exceptions, which are caught at the level being broken out to; placing the nested loops in a function and using return to effect termination of the entire nested loop; or using a label and a goto statement. Neither C nor C++ currently have multilevel break or named loops, and the usual alternative is to use a goto to implement a labeled break.[23] However, the inclusion of this feature has been proposed,[24] and was added to C2Y.,[25] following the Java syntax. Python does not have a multilevel break or continue – this was proposed inPEP 3136, and rejected on the basis that the added complexity was not worth the rare legitimate use.[26]

The notion of multi-level breaks is of some interest intheoretical computer science, because it gives rise to what is today called theKosaraju hierarchy.[27] In 1973S. Rao Kosaraju refined thestructured program theorem by proving that it is possible to avoid adding additional variables in structured programming, as long as arbitrary-depth, multi-level breaks from loops are allowed.[28] Furthermore, Kosaraju proved that a strict hierarchy of programs exists: for every integern, there exists a program containing a multi-level break of depthn that cannot be rewritten as a program with multi-level breaks of depth less thann without introducing added variables.[27]

In his 2004 textbook,David Watt uses Tennent's notion ofsequencer to explain the similarity between multi-level breaks and return statements. Watt notes that a class of sequencers known asescape sequencers, defined as "sequencer that terminates execution of a textually enclosing command or procedure", encompasses both breaks from loops (including multi-level 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.[29]

Middle test
[edit]

The following structure was proposed byDahl in 1972:[30]

looploop       xxx1                           read(char);while test;whilenot atEndOfFile;       xxx2                           write(char);repeat;repeat;

The construction here can be thought of as ado loop with thewhile check in the middle, which allows clearloop-and-a-half logic. Further, by omitting individual components, this single construction can replace several constructions in most programming languages. Ifxxx1 is omitted, we get a loop with the test at the top (a traditionalwhile loop). Ifxxx2 is omitted, we get a loop with the test at the bottom, equivalent to ado while loop in many languages. Ifwhile is omitted, we get an infinite loop. This construction also allows keeping the same polarity of the condition even when in the middle, unlike early exit, which requires reversing the polarity (adding anot),[14] functioning asuntil instead ofwhile.

This structure is not widely supported, with most languages instead usingif ...break for conditional early exit.

This is supported by some languages, such asForth, where the syntax is BEGIN ... WHILE ... REPEAT,[31] and theshell script languagesBourne shell (sh) andbash, where the syntax iswhile ...do ...done oruntil ...do ...done, as:[32][33]

whilestatement-1statement-2...conditiondostatement-astatement-b...done

The shell syntax works because thewhile (oruntil) loop accepts a list of commands as a condition,[34] formally:

whiletest-commands;doconsequent-commands;done

The value (exit status) of the list oftest-commands is the value of thelast command, and these can be separated by newlines, resulting in the idiomatic form above.

Similar constructions are possible in C and C++ with thecomma operator, andother languages with similar constructs, which allow shoehorning a list of statements into the while condition:

while(statement_1,statement_2,condition){statement_a;statement_b;}

While legal, this is marginal, and it is primarily used, if at all, only for short modify-then-test cases, as in:[35]

while(read_string(s),strlen(s)>0){// ...}

Loop variants and invariants

[edit]

Loop variants andloop invariants are used to express correctness of loops.[36]

In practical terms, a loop variant is an integer expression which has an initial non-negative value. The variant's value must decrease during each loop iteration but must never become negative during the correct execution of the loop. Loop variants are used to guarantee that loops will terminate.

A loop invariant is an assertion which must be true before the first loop iteration and remain true after each iteration. This implies that when a loop terminates correctly, both the exit condition and the loop invariant are satisfied. Loop invariants are used to monitor specific properties of a loop during successive iterations.

Some programming languages, such asEiffel contain native support for loop variants and invariants. In other cases, support is an add-on, such as theJava Modeling Language's specification forloop statements inJava.

Loop sublanguage

[edit]

SomeLisp dialects provide an extensive sublanguage for describing Loops. An early example can be found in Conversional Lisp ofInterlisp.Common Lisp[37] provides a Loop macro which implements such a sublanguage.

Loop system cross-reference table

[edit]
Programming languageConditionalLoopEarly exitLoop continuationRedoRetryCorrectness facilities
BeginMiddleEndNumericCollectionGeneralInfinite[1]VariantInvariant
AdaYesYesYesYesarraysNoYesdeep nestedNo
APLYesNoYesYesYesYesYesdeep nested[3]YesNoNo
CYesNoYesNo[2]NoYesNodeep nested[3]deep nested[3]NoNoNoNo
C++YesNoYesNo[2]Yes[9]YesNodeep nested[3]deep nested[3]NoNoNoNo
C#YesNoYesNo[2]YesYesNodeep nested[3]deep nested[3]NoNoNoNo
COBOLYesNoYesYesNoYesNodeep nested[15]deep nested[14]No
Common LispYesYesYesYesbuiltin only[16]YesYesdeep nestedNo
DYesNoYesYesYesYesYes[14]deep nesteddeep nestedNo
EiffelYesNoNoYes[10]YesYesNoone level[10]NoNoNo[11]integer only[13]Yes
F#YesNoNoYesYesNoNoNo[6]NoNo
FORTRAN 77YesNoNoYesNoNoNoone levelYesNoNo
Fortran 90YesNoNoYesNoNoYesdeep nesteddeep nestedNoNo
Fortran 95 and laterYesNoNoYesarraysNoYesdeep nesteddeep nestedNoNo
GoYesNoNoYesbuiltin onlyYesYesdeep nesteddeep nestedNo
HaskellNoNoNoNoYesNoYesNo[6]NoNo
JavaYesNoYesNo[2]YesYesNodeep nesteddeep nestedNonon-native[12]non-native[12]
JavaScriptYesNoYesNo[2]YesYesNodeep nesteddeep nestedNoNoNo
KotlinYesNoYesMaybeYesNoNodeep nesteddeep nestedNoNoNoNo
NaturalYesYesYesYesNoYesYesYesYesYesNo
OCamlYesNoNoYesarrays,listsNoNoNo[6]NoNo
OdinNo[17]NoNoNo[5]builtin onlyYesNo[17]deep nesteddeep nested
PHPYesNoYesNo[2][5]Yes[4]YesNodeep nesteddeep nestedNoNoNoNo
PerlYesNoYesNo[2][5]YesYesNodeep nesteddeep nestedYes
PythonYesNoNoNo[5]YesNoNodeep nested[6]deep nested[6]NoNoNoNo
RebolNo[7]YesYesYesYesNo[8]Yesone level[6]NoNo
RubyYesNoYesYesYesNoYesdeep nested[6]deep nested[6]YesYes
RustYesNoNoNo[5]YesNoYesdeep nesteddeep nestedNoNoNoNo
Standard MLYesNoNoNoarrays,listsNoNoNo[6]NoNo
SwiftYesNoYesNoYesYesNodeep nesteddeep nestedNoNoNoNo
Visual Basic .NETYesNoYesYesYesNoYesone level per type of loopone level per type of loopNoNoNoNo
PowerShellYesNoYesNo[2]YesYesNoYesYesNoNoNoNo
ZigYesNoNoNo[5]builtin onlyNoNodeep nesteddeep nestedNoNoNoNo
  1. awhile (true) does not count as an infinite loop for this purpose, because it is not a dedicated language structure.
  2. abcdefgh C'sfor (init;test;increment) loop is a general loop construct, not specifically a counting one, although it is often used for that.
  3. abc Deep breaks may be accomplished in APL, C, C++ and C# through the use of labels and gotos.
  4. a Iteration over objects wasadded in PHP 5.
  5. abcdef A counting loop can be simulated by iterating over an incrementing list or generator, for instance, Python'srange().
  6. abcde Deep breaks may be accomplished through the use of exception handling.
  7. a There is no special construct, since thewhile function can be used for this.
  8. a There is no special construct, but users can define general loop functions.
  9. a TheC++11 standard introduced therange-based for. In theSTL, there is astd::for_eachtemplate function which can iterate on STLcontainers and call aunary function for each element.[38] The functionality also can be constructed asmacro on these containers.[39]
  10. a Numeric looping is effected by iteration across an integer interval; early exit by including an additional condition for exit.
  11. a Eiffel supports a reserved wordretry, however it is used inexception handling, not loop control.
  12. a RequiresJava Modeling Language (JML) behavioral interface specification language.
  13. a Requires loop variants to be integers; transfinite variants are not supported.Eiffel: Why loop variants are integers
  14. a D supports infinite collections, and the ability to iterate over those collections. This does not require any special construct.
  15. a Deep breaks can be achieved usingGO TO and procedures.
  16. a Common Lisp predates the concept of generic collection type.
  17. ab Odin's generalfor loop supports syntax shortcuts for conditional loop and infinite loop.

Non-local

[edit]

Many programming languages, especially those favoring more dynamic styles of programming, offer constructs for non-local control flow which cause execution to jump from the current execution point to apredeclared point. Notable examples follow.

Condition handling

[edit]

The earliestFortran compilers supported statements for handling exceptional conditions includingIF ACCUMULATOR OVERFLOW,IF QUOTIENT OVERFLOW, andIF DIVIDE CHECK. In the interest of machine independence, they were not included in FORTRAN IV and the Fortran 66 Standard. However, since Fortran 2003 it is possible to test for numerical issues via calls to functions in theIEEE_EXCEPTIONS module.

PL/I has some 22 standard conditions (e.g., ZERODIVIDE SUBSCRIPTRANGE ENDFILE) which can be raised and which can be intercepted by: ONcondition action; Programmers can also define and use their own named conditions.

Like theunstructured 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.

A typical example of syntax:

ONconditionGOTOlabel

Exception handling

[edit]

Many modern languages support anexception handling construct that is structured; does not rely on jump semantics (goto). Generally, exceptional control flow starts with an exception object being thrown (a.k.a. raised). Control then proceeds to the inner-most exception handler for thecall stack. If the handler handles the exception, then flow control reverts to normal. Otherwise, control proceeds outward to containing handlers until one handles the exception or the program reaches the outermost scope and exits. As control flows to progressively outer handlers, aspects that would normally occur such as popping the call stack are handled automatically.

The following C++ code demonstrates structured exception handling. If an exception propagates from the execution ofdoSomething() and the exception object type matches one of the types specified in a catch clause, then that clause is executed. For example, if an exception of typeSomeException is propagated bydoSomething(), then control jumps from line 2 to 4 and the message "Caught SomeException" is printed and then control jumps to after thetry statement, line 8. If an exception of any other type is propagated, then control jumps from line 2 to 6. If no exception, then control jumps from 2 to 8.

try{doSomething();}catch(constSomeException&e)std::println("Caught SomeException: {}",e.what());}catch(...){std::println("Unknown error");}doNextThing();

Many languages use the C++ keywords (throw,try andcatch), but some languages use other keywords. For example, Ada usesexception to introduce an exception handler andwhen instead ofcatch.AppleScript incorporates placeholders in the syntax to extract information about the exception as shown in the following AppleScript code.

trysetmyNumbertomyNumber/0onerrorenumbernfromftotpartialresultprif(e="Can't divide by zero")thendisplay dialog"You must not do that"endtry

In many languages (including Object Pascal, D, Java, C#, and Python) afinally clause at the end of atry statement is executed at the end of the try statement; whether an exception propagates from the rest of thetry or not. The following C# code ensures that the streamstream is closed.

FileStreamstream=null;try{stream=newFileStream("logfile.txt",FileMode.Create);returnProcessStuff(stream);}finally{if(stream!=null){stream.Close();}}

Since this pattern is common, C# provides theusing statement to ensure cleanup. In the following code, even if ProcessStuff() propagates an exception, thestream object is released. Python'swith statement and Ruby's block argument toFile.open are used to similar effect.

using(FileStreamstream=new("logfile.txt",FileMode.Create)){returnProcessStuff(stream);}

Continuation

[edit]
This section is an excerpt fromContinuation.[edit]

Incomputer science, acontinuation is anabstract representation of the control state of acomputer program. A continuation implements (reifies) the program control state, i.e. the continuation is a data structure that represents the computational process at a given point in the process's execution; the created data structure can be accessed by the programming language, instead of being hidden in theruntime environment. Continuations are useful for encoding other control mechanisms in programming languages such asexceptions,generators,coroutines, and so on.

The "current continuation" or "continuation of the computation step" is the continuation that, from the perspective of running code, would be derived from the current point in a program's execution. The termcontinuations can also be used to refer to first-class continuations, which are constructs that give aprogramming language the ability to save the execution state at any point and return to that point at a later point in the program, possibly multiple times.

Generator

[edit]
This section is an excerpt fromGenerator (computer programming).[edit]

Incomputer science, agenerator is aroutine that can be used to control theiteration behaviour of aloop. All generators are alsoiterators.[40] A generator is very similar to afunction that returns anarray, in that a generator hasparameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generatoryields the values one at a time, which requires lessmemory and allows the caller to get started processing the first few values immediately. In short, a generatorlooks like a function butbehaves like aniterator.

Generators can be implemented in terms of more expressive control flow constructs, such ascoroutines or first-classcontinuations.[41] Generators, also known as semicoroutines,[42] are a special case of (and weaker than) coroutines, in that they always yield control back to the caller (when passing a value back), rather than specifying a coroutine to jump to; seecomparison of coroutines with generators.

Coroutine

[edit]
This section is an excerpt fromCoroutine.[edit]
This article'suse ofexternal links may not follow Wikipedia's policies or guidelines. Pleaseimprove this article by removingexcessive orinappropriate external links, and converting useful links where appropriate intofootnote references.(April 2024) (Learn how and when to remove this message)

Coroutines arecomputer program components that allow execution to be suspended and resumed, generalizingsubroutines forcooperative multitasking. Coroutines are well-suited for implementing familiar program components such ascooperative tasks,exceptions,event loops,iterators,infinite lists andpipes.

They have been described as "functions whose execution you can pause".[43]

Melvin Conway coined the termcoroutine in 1958 when he applied it to the construction of anassembly program.[44] The first published explanation of the coroutine appeared later, in 1963.[45]

COMEFROM

[edit]
This section is an excerpt fromCOMEFROM.[edit]

Incomputer programming,COMEFROM is a control flowstatement that causes control flow to jump to the statement after it when control reaches the point specified by the COMEFROM argument. The statement is intended to be the opposite ofgoto and is considered to be more a joke than seriouscomputer science. Often the specified jump point is identified as alabel. For example,COMEFROM x specifies that when control reaches the labelx, then control continues at the statement after the COMEFROM.

A major difference with goto is that goto depends on the local structure of the code, while COMEFROM depends on the global structure. A goto statement transfers control when control reaches the statement, but COMEFROM requires the processor (i.e. interpreter) to scan for COMEFROM statements so that when control reaches any of the specified points, the processor can make the jump. The resulting logic tends to be difficult to understand since there is no indication near a jump point that control will in fact jump. One must study the entire program to see if any COMEFROM statements reference that point.

The semantics of a COMEFROM statement varies byprogramming language. In some languages, the jump occurs before the statement at the specified point is executed and in others the jump occurs after. Depending on the language, multiple COMEFROM statements that reference the same point may be invalid, non-deterministic, executed in some order, or induceparallel or otherwiseconcurrent processing as seen inThreaded Intercal.[citation needed]

COMEFROM was initially seen in lists of jokeassembly language instructions (as 'CMFRM'). It was elaborated upon in aDatamation article by R. Lawrence Clark in 1973,[46] written in response toEdsger Dijkstra's letterGo To Statement Considered Harmful. COMEFROM was eventually implemented in the C-INTERCAL variant of theesoteric programming languageINTERCAL along with the even more obscure 'computed COMEFROM'. There were alsoFortran proposals[47] for 'assigned COME FROM' and a 'DONT' statement (to complement the existing 'DO' loop).

Event-based early exit from nested loop

[edit]

Zahn's construct was proposed in 1974,[48] and discussed inKnuth (1974). A modified version is presented here.

exitwhen EventAor EventBor EventC;       xxxexits       EventA: actionA       EventB: actionB       EventC: actionCendexit;

exitwhen is used to specify the events which may occur withinxxx,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 afterendexit. 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 toexception handling, and exceptions or similar constructs are used for this purpose in many languages.

The following simple example involves searching a two-dimensional table for a particular item.

exitwhen foundor missing;for I := 1to Ndofor J := 1to Mdoif table[I,J] = targetthen found;       missing;exits       found:   print ("item is in table");       missing: print ("item is not in table");endexit;

See also

[edit]

References

[edit]
  1. ^Payer, Mathias; Kuznetsov, Volodymyr."On differences between the CFI, CPS, and CPI properties".nebelwelt.net. Retrieved2016-06-01.
  2. ^"Adobe Flash Bug Discovery Leads To New Attack Mitigation Method".Dark Reading. 10 November 2015. Retrieved2016-06-01.
  3. ^Endgame."Endgame to Present at Black Hat USA 2016".www.prnewswire.com (Press release). Retrieved2016-06-01.
  4. ^"Nested Loops in C with Examples".GeeksforGeeks. 2019-11-25. Retrieved2024-03-14.
  5. ^"Python Nested Loops".www.w3schools.com. Retrieved2024-03-14.
  6. ^Dean, Jenna (2019-11-22)."Nested Loops".The Startup. Retrieved2024-03-14.
  7. ^Knuth, Donald E. (1974). "Structured Programming withgo to Statements".Computing Surveys.6 (4):261–301.CiteSeerX 10.1.1.103.6084.doi:10.1145/356635.356640.S2CID 207630080.
  8. ^abcdeRoberts, E. [1995] "Loop Exits and Structured Programming: Reopening the DebateArchived 2014-07-25 at theWayback Machine," ACM SIGCSE Bulletin, (27)1: 268–272.
  9. ^"Endless loop dictionary definition".Archived from the original on 2020-08-01. Retrieved2020-01-22.
  10. ^"What is infinite loop (endless loop)".Archived from the original on 2019-07-15. Retrieved2020-01-22.
  11. ^ab"Messy Loop Conditions".WikiWikiWeb. 2014-11-03.
  12. ^abcKnuth 1974, p. 278, Simple Iterations.
  13. ^Edsger W. Dijkstra, personal communication toDonald Knuth on 1974-01-03, cited inKnuth (1974, p. 278, Simple Iterations)
  14. ^abcKnuth 1974, p. 279.
  15. ^"What is a loop and how we can use them?". Archived fromthe original on 2020-07-28. Retrieved2020-05-25.
  16. ^"redo - perldoc.perl.org".perldoc.perl.org. Retrieved2020-09-25.
  17. ^"control_expressions - Documentation for Ruby 2.4.0".docs.ruby-lang.org. Retrieved2020-09-25.
  18. ^"control_expressions - Documentation for Ruby 2.3.0".docs.ruby-lang.org. Retrieved2020-09-25.
  19. ^Is a common way to solve theloop-and-a-half problem.
  20. ^Advanced Bash Scripting Guide:11.3. Loop Control
  21. ^PHP Manual: "break"
  22. ^perldoc:last
  23. ^comp.lang.c FAQ list · "Question 20.20b"
  24. ^"named-loops".open-std.org. 18 September 2024.
  25. ^"Information technology — Programming languages — C"(PDF).open-std.org. 4 May 2025.
  26. ^[Python-3000] Announcing PEP 3136, Guido van Rossum
  27. ^abKozen, Dexter (2008). "The Böhm–Jacopini Theorem is False, Propositionally".Mathematics of Program Construction(PDF). Lecture Notes in Computer Science. Vol. 5133. pp. 177–192.CiteSeerX 10.1.1.218.9241.doi:10.1007/978-3-540-70594-9_11.ISBN 978-3-540-70593-2.
  28. ^Kosaraju, S. Rao. "Analysis of structured programs," Proc. Fifth Annual ACM Syrup.Theory of Computing, (May 1973), 240-252; also in J. Computer and System Sciences, 9,3 (December 1974), cited byKnuth (1974).
  29. ^David Anthony Watt; William Findlay (2004).Programming language design concepts. John Wiley & Sons. pp. 215–221.ISBN 978-0-470-85320-7.
  30. ^Dahl & Dijkstra & Hoare, "Structured Programming" Academic Press, 1972.
  31. ^"6. Throw It For a Loop".
  32. ^"3.2.5.1 Looping Constructs",The GNU Bash Reference Manual, 2025-05-18
  33. ^"How could a language make the loop-and-a-half less error-prone?".Stack Exchange: Programming Language Design and Implementation.
  34. ^"3.2.4 Lists of Commands",The GNU Bash Reference Manual, 2025-05-18
  35. ^"What does the comma operator , do?".Stack Overflow.
  36. ^Meyer, Bertrand (1991).Eiffel: The Language. Prentice Hall. pp. 129–131.
  37. ^"Common Lisp LOOP macro".
  38. ^for_each. Sgi.com. Retrieved on 2010-11-09.
  39. ^Chapter 1. Boost.ForeachArchived 2010-01-29 at theWayback Machine. Boost-sandbox.sourceforge.net (2009-12-19). Retrieved on 2010-11-09.
  40. ^What is the difference between an Iterator and a Generator?
  41. ^Kiselyov, Oleg (January 2004)."General ways to traverse collections in Scheme".
  42. ^Anthony Ralston (2000).Encyclopedia of computer science. Nature Pub. Group.ISBN 978-1-56159-248-7. Retrieved11 May 2013.
  43. ^"How the heck does async/await work in Python 3.5?".Tall, Snarky Canadian. 2016-02-11.Archived from the original on 2023-01-10. Retrieved2023-01-10.
  44. ^Knuth, Donald Ervin (1997).Fundamental Algorithms(PDF). The Art of Computer Programming. Vol. 1 (3rd ed.). Addison-Wesley. Section 1.4.5: History and Bibliography, pp. 229.ISBN 978-0-201-89683-1.Archived(PDF) from the original on 2019-10-21.
  45. ^Conway, Melvin E. (July 1963)."Design of a Separable Transition-diagram Compiler"(PDF).Communications of the ACM.6 (7). ACM:396–408.doi:10.1145/366663.366704.ISSN 0001-0782.S2CID 10559786.Archived(PDF) from the original on 2022-04-06. Retrieved2019-10-21 – via ACM Digital Library.
  46. ^Clarke, Lawrence,"We don't know where to GOTO if we don't know where we've COME FROM. This linguistic innovation lives up to all expectations.",Datamation (article), archived fromthe original on 2018-07-16, retrieved2004-09-24.
  47. ^Modell, Howard; Slater, William (April 1978)."Structured programming considered harmful".ACM SIGPLAN Notices.13 (4):76–79.doi:10.1145/953411.953418. Retrieved18 July 2014.
  48. ^Zahn, C. T."A control statement for natural top-down structured programming" presented at Symposium on Programming Languages, Paris, 1974.

Further reading

[edit]
  • Hoare, C. A. R. "Partition: Algorithm 63," "Quicksort: Algorithm 64," and "Find: Algorithm 65." Comm. ACM 4, 321–322, 1961.

External links

[edit]
The WikibookAda Programming has a page on the topic of:Control
The WikibookComputer Programming has a page on the topic of:Control
Retrieved from "https://en.wikipedia.org/w/index.php?title=Control_flow&oldid=1320701506"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp