Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Conditional (computer programming)

From Wikipedia, the free encyclopedia
Control flow statement that branches according to a Boolean expression
If-then-else flow diagram
A nestedif–then–else flow diagram

Incomputer programming, aconditionalstatement directs programcontrol flow based on the value of acondition; aBoolean expression. A conditionalexpression evaluates to a value without theside-effect of changing control flow.

Many programming languages (such asC) have distinct conditional statements and expressions. In purefunctional programming, a conditional expression does not have side-effects, many functional programming languages with conditional expressions (such as Lisp) support side-effects.

Conditional statement

[edit]

If-then-else statement

[edit]
"if-then-else" redirects here. For the album, seeIf Then Else. For the TV episode, seeIf-Then-Else.

Although the syntax of an if-then-else statement varies by language, the general syntax is shown aspseudocode below. The part represented by thecondition placeholder is an expression that evaluates to either true or false. If true, control passes toconsequent and when complete to afterend if. If false, control passes toalternative and when complete to afterend if. As the else clause is optional, theelsealternative part can be omitted. Typically, bothconsequent andalternative can be either a single statement or ablock of statements.

ifconditionthenconsequentelsealternativeendif

The following example, also in pseudocode, replaces placeholders with example logic.

ifstock=0thenmessage='order new stock'elsemessage='there is stock'endif

History and development

[edit]

In early programming languages, especially dialects ofBASIC, an if–then-else statement could only containgoto statements but this tended to result in hard-to-readspaghetti code. As a result,structured programming, which supports control flow via code blocks, gained in popularity, until it became the norm in most BASIC variants and all languages. Such mechanisms and principles were based on theALGOL family of languages, includingPascal andModula-2. While it is possible to use goto in a structured way, structured programming makes this easier. A structured if–then–else statement is one of the key elements of structured programming, and it is present in most popular languages such asC,Java,JavaScript andVisual Basic.

Dangling else

[edit]
Main article:Dangling else

The convention is that anelse clause, like thethen clause, responds to the nearest precedingif clause; however, the semantics in some early languages, such asALGOL 60, ofnested conditionals, were less than clear; that is to say, the syntax was inadequate to specify one-and-always-the-same predicateif clause. Thus, the parser might randomly pair theelse with any one of the perhaps manifoldif clauses in the intended nested hierarchy.

For example, take the statement:
ifAthenifBthenSelseS2
or the same statement but indented for clarity:
ifAthenifBthenSelseS2
may beparsed either as meaning:
ifAthen(ifBthenS)elseS2end
ifAthen(ifBthenS)elseS2end
or as meaning:
ifAthen(ifBthenSelseS2)
ifAthen(ifBthenSelseS2)end

This is known as thedangling else problem. It is resolved in various ways, depending on the language (in some, by means of explicit block-ending syntax (such asend if ) or a block enclosure, such as curly brackets ({} ).

Chaining

[edit]

Chaining conditionals is often provided in a language via an else-if construct. Only the statements following the first condition that is true are executed. Other statements are skipped. In placeholder pseudocode:

ifcondition1thenblock1elseifcondition2thenblock2elseifcondition3thenblock3...elseblock4endif

In the following pseudocode, a shop offers as much as a 30% discount for an item. If the discount is 10%, then the first if statement is true and "you have to pay $30" is printed. All other statements below that first if statement are skipped.

ifdiscount<11%thenprint"You have to pay $30."elseifdiscount<21%thenprint"You have to pay $20."elseifdiscount<31%thenprint"You have to pay $10."endif

Only oneend if is needed if one useselse if instead ofelse followed byif.

InALGOL 68, the 1968 “Draft Report” (circulated as a supplement toALGOL Bulletin no. 26) still used thebold keywordelsf in “contracted” conditionals.[1]The spellingelif was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68” (1973), which lists both thebold wordsif ~then ~elif ~else ~fi and their “brief” symbols, whereelif corresponds to|: in the compact form( ~ | ~ |: ~ | ~ | ~ ).[2]

InAda, theelseif keyword issyntactic sugar for the two wordselseif.PHP also supports anelseif keyword[3] both for its curly brackets or colon syntaxes.Perl andRuby provide the keywordelsif to avoid the large number of braces that would be required by multipleif andelse statements.Python uses the special keywordelif because structure is denoted by indentation rather than braces, so a repeated use ofelse andif would require increased indentation after every condition.Visual Basic, supportsElseIf.[4] Similarly, the earlierUNIX shells (later gathered up to the POSIX shell syntax[5]) useelif too, but giving the choice of delimiting with spaces, line breaks, or both.

However, in many languages more directly descended from Algol, such asSimula,Pascal, BCPL andC, this special syntax for theelse if construct is not present, nor is it present in the many syntactical derivatives of C, such asJava,ECMAScript, and so on. This works because in these languages, anysingle statement (in this caseif cond...) can follow a conditional without being enclosed in a block.[clarification needed]

If all terms in the sequence of conditionals are testing the value of a single expression (e.g.,if x = 0else if x = 1else if x = 2 ...), an alternative is theswitch statement. In a language that does not have a switch statement, these can be encoded as a chained if-then-else.

Switch statement

[edit]

Aswitch statement supports multiway branching; often comparing the value of an expression with constant values and transferring control to the code of the first match. There is usually a provision for a default action if no match is found. Anoptimizing compiler may use acontrol table to implement the logic of a switch statement. In a dynamic language, 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 aregular expression matching any string.

Guarded conditional

[edit]

TheGuarded Command Language (GCL) ofEdsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valuedguard (corresponding to acondition) and its corresponding statement. In GCL, exactly one of the statements whose guards is true is evaluated, but which one is arbitrary. In this code

if G0 → S0 □ G1 → S1... □ Gn → Snfi

the Gi's are the guards and the Si's are the statements. If none of the guards is true, the program's behavior is undefined.

GCL is intended primarily for reasoning about programs, but similar notations have been implemented inConcurrent Pascal andoccam.

Arithmetic if

[edit]

The earliest conditional statement in Fortran, up toFortran 77, was the arithmetic if statement which jumped to one of three labels depending on whether a value (of type integer, real, or double precision) is <0, 0, or >0.[6]

In the following code, control passes to one of the labels based on the value ofe.

IF(e)label1,label2,label3

This is equivalent to the following sequence.

e_temp=eIF(e_temp.LT.0)GOTOlabel1IF(e_temp.EQ.0)GOTOlabel2IF(e_temp.GT.0)GOTOlabel3

As it acts likegoto, arithmetic if is unstructured; notstructured programming. It was the only conditional statement in the original implementation of Fortran on theIBM 704 computer. On that computer, the test-and-branch op-code had three addresses for those three states. Other computers would have "flag" registers such as positive, zero, negative, even, overflow, carry, associated with the last arithmetic operations and would use instructions such as 'Branch if accumulator negative' then 'Branch if accumulator zero' or similar. Note that the expression is evaluatedonce only, and in cases such as integer arithmetic where overflow may occur, the overflow or carry flags would be considered also.

The Arithmetic IF statement was listed as obsolescent starting with the Fortran 90 Standard. It was deleted from the Fortran 2018 Standard. Nonetheless most compilers continue to support it for compatibility with legacy codes.

In Smalltalk

[edit]

In contrast to other languages, inSmalltalk the conditional statement is not alanguage construct but defined in the classBoolean as an abstract method that takes two parameters, bothclosures.Boolean has two subclasses,True andFalse, which both define the method,True executing the first closure only,False executing the second closure only.[7]

var=conditionifTrue: ['foo' ]ifFalse: ['bar' ]

In JavaScript

[edit]

JavaScript supports if-else statements similar toC syntax. The following example has conditionalMath.random()<0.5 which is true if the random float (value between 0 and 1) is greater than 0.5. The statement uses it to randomly choose between outputtingYou got Heads! orYou got Tails!.

if(Math.random()<0.5){console.log("You got Heads!");}else{console.log("You got Tails!");}

Conditionals can be chained as shown below:

varx=Math.random();if(x<1/3){console.log("One person won!");}elseif(x<2/3){console.log("Two people won!");}else{console.log("It's a three-way tie!");}

Lambda calculus

[edit]

InLambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions:

true = λx. λy. xfalse = λx. λy. yifThenElse = (λc. λx. λy. (c x y))
  1. true takes up to two arguments and once both are provided (seecurrying), it returns the first argument given.
  2. false takes up to two arguments and once both are provided(seecurrying), it returns the second argument given.
  3. ifThenElse takes up to three arguments and once all are provided, it passes both second and third argument to the first argument(which is a function that given two arguments, and produces a result). We expectifThenElse to only take true or false as an argument, both of which project the given two arguments to their preferred single argument, which is then returned.

Note: ififThenElse is passed two functions as the left and right conditionals; it isnecessary to also pass an empty tuple() to the result ofifThenElse in order to actually call the chosen function, otherwiseifThenElse will just return thefunction object without getting called.

In a system where numbers can be used without definition (like Lisp, Traditional paper math, so on), the above can be expressed as a single closure below:

((λtrue.λfalse.λifThenElse.(ifThenElsetrue23))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))

Here,true, false, andifThenElse are bound to their respective definitions which are passed to their scope at the end of their block.

A working JavaScript analogy(using only functions of single variable for rigor) to this is as follows:

varcomputationResult=((_true=>_false=>_ifThenElse=>_ifThenElse(_true)(2)(3))(x=>y=>x)(x=>y=>y)(c=>x=>y=>c(x)(y)));

The code above with multivariable functions looks like this:

varcomputationResult=((_true,_false,_ifThenElse)=>_ifThenElse(_true,2,3))((x,y)=>x,(x,y)=>y,(c,x,y)=>c(x,y));

Another version of the earlier example without a system where numbers are assumed is below.

The first example shows the first branch being taken, while second example shows the second branch being taken.

((λtrue.λfalse.λifThenElse.(ifThenElsetrue(λFirstBranch.FirstBranch)(λSecondBranch.SecondBranch)))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))((λtrue.λfalse.λifThenElse.(ifThenElsefalse(λFirstBranch.FirstBranch)(λSecondBranch.SecondBranch)))(λx.λy.x)(λx.λy.y)(λc.λl.λr.clr))

Smalltalk uses a similar idea for its true and false representations, withTrue andFalse being singleton objects that respond to messagesifTrue/ifFalse differently.

Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugarifathenbelsec construct which unlikeifThenElse does not compose unlesseither wrapped in another function or re-implemented as shown in The Haskell section of this page.

Conditional expression

[edit]
See also:Ternary conditional operator

Many languages support a conditional expression, which unlike a statement evaluates to a value instead of controlling control flow. The concept of conditional expression was first developed byJohn McCarthy during his research into symbolic processing and LISP in the late 1950s.

Examples

[edit]

Algol

[edit]

ALGOL 60 and some other members of theALGOL family allowif–then–else as an expression. The idea of including conditional expressions was suggested by John McCarthy, though the ALGOL committee decided to use English words rather than McCarthy's mathematical syntax:

myvariable:=ifx>20then1else2


ALGOL 68

[edit]

Compound statements are all terminated (guarded) by distinctive closing brackets:

  • IF choice clauses:
IF conditionTHEN statements [ELSE statements ]FI "brief" form:  ( condition | statements | statements )
IF condition1THEN statementsELIF condition2THEN statements [ELSE statements ]FI "brief" form:  ( condition1 | statements |: condition2 | statements | statements )

This scheme not only avoids thedangling else problem but also avoids having to useBEGIN andEND in embeddedstatement sequences.

  • CASE choice clauses:
CASE switchIN statements, statements,... [OUT statements ]ESAC "brief" form:  ( switch | statements,statements,... | statements )
CASE switch1IN statements, statements,...OUSE switch2IN statements, statements,... [OUT statements ]ESAC "brief" form ofCASE statement:  ( switch1 | statements,statements,... |: switch2 | statements,statements,... | statements )

Choice clause example withBrief symbols:

PROC days in month = (INT year, month)INT:  (month|    31,    (year÷×4=0 ∧ year÷×100≠0  ∨  year÷×400=0 | 29 | 28 ),    31, 30, 31, 30, 31, 31, 30, 31, 30, 31  );

Lisp

[edit]

Conditional expressions have always been a fundamental part ofLisp . In pure LISP, theCOND function is used. In dialects such asScheme,Racket andCommon Lisp :

;; Scheme(define(myvariablex)(if(>x12)12)); Assigns 'myvariable' to 1 or 2, depending on the value of 'x'
;; Common Lisp(let((x10))(setqmyvariable(if(>x12)24))); Assigns 'myvariable' to 2
See also:McCarthy Formalism

Haskell

[edit]
Main article:Haskell (programming language)

InHaskell 98, there is only anif expression, noif statement, and theelse part is compulsory, as every expression must have some value.[8] Logic that would be expressed with conditionals in other languages is usually expressed withpattern matching in recursive functions.

Because Haskell islazy, it is possible to write control structures, such asif, as ordinary expressions; the lazy evaluation means that anif function can evaluate only the condition and proper branch (where a strict language would evaluate all three). It can be written like this:[9]

if'::Bool->a->a->aif'Truex_=xif'False_y=y

C-like languages

[edit]

C and related languages support aternary operator that provides for conditional expressions like:

condition ?true-value :false-value

Ifcondition is true, then the expression evaluates totrue-value; otherwise tofalse-value. In the following code, r is assigned to "foo" if x > 10; otherwise to "bar".

r=x>10?"foo":"bar";

To accomplish the same using an if-statement, this would take more than one statement, and require mentioningr twice:

if(x>10)r="foo";elser="bar";

Some argue that the explicit if-then statement is easier to read and that it may compile to more efficient code than the ternary operator,[10] while others argue that concise expressions are easier to read and better since they have less repeated clauses.

Visual Basic

[edit]
Main article:Visual Basic

InVisual Basic and some other languages, a function calledIIf is provided, which can be used as a conditional expression. However, it does not behave like a true conditional expression, because both the true and false branches are always evaluated; it is just that the result of one of them is thrown away, while the result of the other is returned by the IIf function.

Tcl

[edit]
Main article:Tcl

InTclif is not a keyword but a function (in Tcl known as command orproc). For example

if{$x>10}{puts"Foo!"}

invokes a function namedif passing 2 arguments: The first one being the condition and the second one being the true branch. Both arguments are passed as strings (in Tcl everything within curly brackets is a string).

In the above example the condition is not evaluated before calling the function. Instead, the implementation of theif function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.[11]

Such a behavior is possible by usinguplevel andexpr commands. Uplevel makes it possible to implement new control constructs as Tcl procedures (for example, uplevel could be used to implement the while construct as a Tcl procedure).[12]

Becauseif is actually a function it also returns a value. The return value from the command is the result of the body script that was executed, or anempty string if none of the expressions was non-zero and there was no bodyN.[13]

Rust

[edit]
Main article:Rust (programming language)

InRust,if is always an expression. It evaluates to the value of whichever branch is executed, or to the unit type() if no branch is executed. If a branch does not provide a return value, it evaluates to() by default. To ensure theif expression's type is known atcompile time, each branch must evaluate to a value of the same type. For this reason, anelse branch is effectively compulsory unless the other branches evaluate to(), because anif without anelse can always evaluate to() by default.[14]

The following assignsr to 1 or 2 depending on the value of x.

letr=ifx>20{1}else{2};

Values can be omitted when not needed.

ifx>20{println!("x is greater than 20");}

Pattern matching

[edit]

Pattern matching is an alternative to conditional statements (such as if–then–else and switch). It is available in many languages with functional programming features, such asWolfram Language,ML and many others. Here is a simple example written in theOCaml language:

matchfruitwith|"apple"->cookpie|"coconut"->cookdango_mochi|"banana"->mix;;

The power of pattern matching is the ability toconcisely match not only actions but alsovalues to patterns of data. Here is an example written inHaskell which illustrates both of these features:

map_[]=[]mapf(h:t)=fh:mapft

This code defines a functionmap, which applies the first argument (a function) to each of the elements of the second argument (a list), and returns the resulting list. The two lines are the two definitions of the function for the two kinds of arguments possible in this case – one where the list is empty (just return an empty list) and the other case where the list is not empty.

Pattern matching is not strictly speakingalways a choice construct, because it is possible in Haskell to write only one alternative, which is guaranteed to always be matched – in this situation, it is not being used as a choice construct, but simply as a way to bind names to values. However, it is frequently used as a choice construct in the languages in which it is available.

Hash-based conditionals

[edit]

In programming languages that haveassociative arrays or comparable data structures, such asPython,Perl,PHP orObjective-C, it is idiomatic to use them to implement conditional assignment.[15]

pet=input("Enter the type of pet you want to name: ")known_pets={"Dog":"Fido","Cat":"Meowsles","Bird":"Tweety",}my_name=known_pets[pet]

In languages that haveanonymous functions or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a hash as adispatch table.

Branch predication

[edit]

An alternative to conditional branch instructions isbranch predication. Predication is anarchitectural feature that enables instructions to be conditionally executed instead of modifying thecontrol flow.

Choice system cross reference

[edit]

This table refers to the most recent language specification of each language. For languages that do not have a specification, the latest officially released implementation is referred to.

Programming languageStructured ifswitch–select–caseConditional expressionsArithmetic ifPattern matching[A]
thenelseelse–if
AdaYesYesYesYesYesNoNo
ALGOL-60YesYesUnneeded[C]NoYesNoNo
ALGOL 68YesYesYesYesYesYes -case clauseYes - Conformity clause
APLNoYesYesYesYesNoNo
Bash shellYesYesYesYesYesNoYes
C,C++NoYesUnneeded[B][C]Fall-throughYesNoNo
C#NoYesUnneeded[B][C]YesYesNoNo
COBOLUnneededYesUnneeded[C]YesNoNoNo
EiffelYesYesYesYesYesNoNo
F#YesYesYesYes[D]YesNoYes
FortranYesYesYesYesYes[G]Yes[I]No
GoNoYesUnneeded[C]YesNoNoNo
HaskellYesNeededUnneeded[C]Yes[D]YesNoYes
JavaNoYesUnneeded[C]Fall-through[16]YesNoNo
ECMAScript (JavaScript)NoYesUnneeded[C]Fall-through[17]YesNoNo
MathematicaNoYesYesYesYesNoYes
OberonYesYesYesYesNoNoNo
PerlNoYesYesYesYesNoNo
PHPNoYesYesFall-throughYesNoYes
Pascal,Object Pascal (Delphi)YesYesUnneededYesNoNoNo
PythonNoYesYesYesYesNoYes
QuickBASICYesYesYesYesNoNoNo
RubyYesYesYesYesYesNoYes[H]
RustNoYesYesYes[D]YesNoYes
ScalaNoYesUnneeded[C]Fall-through[citation needed]YesNoYes
SQLYes[F]YesYesYes[F]YesNoNo
SwiftNoYesYesYesYesNoYes
TclNoYesYesYesYesNoYes
Visual Basic, classicYesYesYesYesYesNoNo
Visual Basic .NETYesYesYesYesYesNoNo
Windows PowerShellNoYesYesFall-throughYesNoNo
  1. ^ This refers to pattern matching as a distinct conditional construct in the programming language – as opposed to mere string pattern matching support, such asregular expression support.
  2. 12 An #ELIF directive is used in thepreprocessor sub-language that is used to modify the code before compilation; and toinclude other files.
  3. 123456 The often-encounteredelse if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independentif then else statements combined with a particular source code layout. However, this also means that a distinct else–if construct is not really needed in these languages.
  4. 123 Case-expressions in Haskell and match-expressions in F# and Haskell allow both switch-case and pattern matching usage.
  5. ^ In a Rubycase construct,regular expression matching is among the conditional flow-control alternatives available. For an example, seethis Stack Overflow question.
  6. 12 SQL has two similar constructs that fulfill both roles, both introduced inSQL-92. A "searchedCASE" expressionCASEWHENcond1THENexpr1WHENcond2THENexpr2[...]ELSEexprDfltEND works likeif ... else if ... else, whereas a "simpleCASE" expression:CASEexprWHENval1THENexpr1[...]ELSEexprDfltEND works like a switch statement. For details and examples seeCase (SQL).
  7. ^ Fortran 90 added theMERGE intrinsic. Fortran 2023 added the C-like ternary operator.
  8. ^ Pattern matching was added in Ruby 3.0.[18] Some pattern matching constructs are still experimental.
  9. ^ Arithmeticif was marked as obsolescent in Fortran 90. It was deleted as of the Fortran 2018 Standard.

See also

[edit]

References

[edit]
  1. ^Draft Report on the Algorithmic Language ALGOL 68(PDF) (Report). Mathematisch Centrum (Supplement to Algol Bulletin 26). 1968. p. 55.
  2. ^"Revised Report on the Algorithmic Language ALGOL 68"(PDF).Algol Bulletin (Supplement 47) / Numer. Math.:118–121. 1973.symbol tables: "boldelse if" → "elif"; "briefelse if" → "|:")
  3. ^PHP elseif syntax
  4. ^Visual BasicElseIf syntax
  5. ^POSIX standard shell syntax
  6. ^"American National Standard Programming Language FORTRAN". 1978-04-03. Archived fromthe original on 2007-10-11. Retrieved2007-09-09.
  7. ^"VisualWorks: Conditional Processing". 2006-12-16. Archived fromthe original on 2007-10-22. Retrieved2007-09-09.
  8. ^Haskell 98 Language and Libraries: The Revised Report
  9. ^"If-then-else Proposal on HaskellWiki"
  10. ^"Efficient C Tips #6 – Don't use the ternary operator « Stack Overflow". Embeddedgurus.com. 2009-02-18. Retrieved2012-09-07.
  11. ^"New Control Structures".Tcler's wiki. RetrievedAugust 21, 2020.
  12. ^"uplevel manual page".www.tcl.tk. RetrievedAugust 21, 2020.
  13. ^"if manual page".www.tcl.tk. RetrievedAugust 21, 2020.
  14. ^"If and if let expressions". RetrievedNovember 1, 2020.
  15. ^"Pythonic way to implement switch/case statements". Archived fromthe original on 2015-01-20. Retrieved2015-01-19.
  16. ^Java.sun.com, Java Language Specification, 3rd Edition.
  17. ^Ecma-international.orgArchived 2015-04-12 at theWayback Machine ECMAScript Language Specification, 5th Edition.
  18. ^"Pattern Matching".Documentation for Ruby 3.0.

External links

[edit]
Look upthen orelse in Wiktionary, the free dictionary.
Retrieved from "https://en.wikipedia.org/w/index.php?title=Conditional_(computer_programming)&oldid=1319312034"
Category:
Hidden categories:

[8]ページ先頭

©2009-2025 Movatter.jp