GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing en.wikipedia.org — Conditional (computer programming) - Wikipedia (Redirected from If statement) In computer programming, a conditional statement directs program control flow based on the value of a condition; a Boolean expression. A conditional expression evaluates to a value without the side-effect of changing control flow. Many programming languages (such as C) have distinct conditional statements and expressions. In pure functional programming, a conditional expression does not have side-effects, many functional programming languages with conditional expressions (such as Lisp) support side-effects. Conditional statementIf-then-else statement"if-then-else" redirects here. For the album, see If Then Else. For the TV episode, see If-Then-Else.
Although the syntax of an if-then-else statement varies by language, the general syntax is shown as pseudocode below. The part represented by the condition placeholder is an expression that evaluates to either true or false. If true, control passes to consequent and when complete to after if condition then consequent else alternative end if The following example, also in pseudocode, replaces placeholders with example logic. if stock = 0 then message = 'order new stock' else message = 'there is stock' end if History and developmentIn early programming languages, especially dialects of BASIC, an if–then-else statement could only contain goto statements but this tended to result in hard-to-read spaghetti 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 the ALGOL family of languages, including Pascal and Modula-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 as C, Java, JavaScript and Visual Basic. Dangling elseMain article: Dangling else
The convention is that an For example, take the statement:
if A then if B then S else S2 or the same statement but indented for clarity:
if A then if B then S else S2 may be parsed either as meaning:
if A then (if B then S) else S2 end if A then (if B then S) else S2 end or as meaning:
if A then (if B then S else S2) if A then (if B then S else S2) end This is known as the dangling else problem. It is resolved in various ways, depending on the language (in some, by means of explicit block-ending syntax (such as ChainingChaining 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: if condition1 then block1 else if condition2 then block2 else if condition3 then block3 ... else block4 end if 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. if discount < 11% then print "You have to pay $30." else if discount < 21% then print "You have to pay $20." else if discount < 31% then print "You have to pay $10." end if Only one In ALGOL 68, the 1968 “Draft Report” (circulated as a supplement to ALGOL Bulletin no. 26) still used the bold keyword elsf in “contracted” conditionals.[1]
The spelling elif was then standardized in the “Revised Report on the Algorithmic Language ALGOL 68” (1973), which lists both the bold words In Ada, the elseif keyword is syntactic sugar for the two words However, in many languages more directly descended from Algol, such as Simula, Pascal, BCPL and C, this special syntax for the If all terms in the sequence of conditionals are testing the value of a single expression (e.g., Switch statementA switch 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. An optimizing compiler may use a control 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 to pattern matching, as in the shell script example on the right, where the '*)' implements the default case as a regular expression matching any string. Guarded conditionalThe Guarded Command Language (GCL) of Edsger Dijkstra supports conditional execution as a list of commands consisting of a Boolean-valued guard (corresponding to a condition) 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 → Sn fi 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 in Concurrent Pascal and occam. Arithmetic ifThe earliest conditional statement in Fortran, up to Fortran 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 of IF (e) label1, label2, label3 This is equivalent to the following sequence. e_temp = e IF (e_temp .LT. 0) GOTO label1 IF (e_temp .EQ. 0) GOTO label2 GOTO label3 As it acts like goto, arithmetic if is unstructured, not structured, programming. It was the only conditional statement in the original implementation of Fortran on the IBM 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 evaluated once 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 SmalltalkIn contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class var = condition ifTrue: [ 'foo' ] ifFalse: [ 'bar' ] In JavaScriptJavaScript supports if-else statements similar to C syntax. The following example has conditional if (Math.random() < 0.5) { console.log("You got Heads!"); } else { console.log("You got Tails!"); } Conditionals can be chained as shown below: var x = Math.random(); if (x < 1/3) { console.log("One person won!"); } else if (x < 2/3) { console.log("Two people won!"); } else { console.log("It's a three-way tie!"); } Lambda calculusIn Lambda calculus, the concept of an if-then-else conditional can be expressed using the following expressions: true = λx. λy. x false = λx. λy. y ifThenElse = (λc. λx. λy. (c x y))
Note: if ifThenElse is passed two functions as the left and right conditionals; it is necessary to also pass an empty tuple 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. (ifThenElse true 2 3) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r)) Here, true, false, and ifThenElse 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: var computationResult = ((_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: var computationResult = ((_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. (ifThenElse true (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch)) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r)) ((λtrue. λfalse. λifThenElse. (ifThenElse false (λFirstBranch. FirstBranch) (λSecondBranch. SecondBranch)) )(λx. λy. x)(λx. λy. y)(λc. λl. λr. c l r)) Smalltalk uses a similar idea for its true and false representations, with Haskell used to use this exact model for its Boolean type, but at the time of writing, most Haskell programs use syntactic sugar Conditional expressionSee 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 by John McCarthy during his research into symbolic processing and LISP in the late 1950s. ExamplesAlgolALGOL 60 and some other members of the ALGOL family allow myvariable := if x > 20 then 1 else 2 Compound statements are all terminated (guarded) by distinctive closing brackets:
IF condition THEN statements [ ELSE statements ] FI "brief" form: ( condition | statements | statements ) IF condition1 THEN statements ELIF condition2 THEN statements [ ELSE statements ] FI "brief" form: ( condition1 | statements |: condition2 | statements | statements ) This scheme not only avoids the dangling else problem but also avoids having to use
CASE switch IN statements, statements,... [ OUT statements ] ESAC "brief" form: ( switch | statements,statements,... | statements ) CASE switch1 IN statements, statements,... OUSE switch2 IN statements, statements,... [ OUT statements ] ESAC "brief" form of CASE statement: ( switch1 | statements,statements,... |: switch2 | statements,statements,... | statements ) Choice clause example with Brief 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
);
LispConditional expressions have always been a fundamental part of Lisp . In pure LISP, the ;; Scheme (define (myvariable x) (if (> x 12) 1 2)) ; Assigns 'myvariable' to 1 or 2, depending on the value of 'x' ;; Common Lisp (let ((x 10)) (setq myvariable (if (> x 12) 2 4))) ; Assigns 'myvariable' to 2 See also: McCarthy Formalism
HaskellMain article: Haskell (programming language)
In Haskell 98, there is only an if expression, no if statement, and the Because Haskell is lazy, it is possible to write control structures, such as if, as ordinary expressions; the lazy evaluation means that an if 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 -> a if' True x _ = x if' False _ y = y C-like languagesC and related languages support a ternary operator that provides for conditional expressions like: condition ? true-value : false-value If condition is true, then the expression evaluates to true-value; otherwise to false-value. In the following code, r is assigned to "foo" if x > 10, and to "bar" if not. r = x > 10 ? "foo" : "bar"; To accomplish the same using an if-statement, this would take more than one statement, and require mentioning if (x > 10) r = "foo"; else r = "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 BasicMain article: Visual Basic
In Visual Basic and some other languages, a function called TclMain article: Tcl (programming language)
In Tcl if {$x > 10} { puts "Foo!" } invokes a function named In the above example the condition is not evaluated before calling the function. Instead, the implementation of the Such a behavior is possible by using Because RustMain article: Rust (programming language)
In Rust, The following assigns let r = if x > 20 { 1 } else { 2 }; Values can be omitted when not needed. if x > 20 { println!("x is greater than 20"); } Pattern matchingPattern 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 as Wolfram Language, ML and many others. Here is a simple example written in the OCaml language: match fruit with | "apple" -> cook pie | "coconut" -> cook dango_mochi | "banana" -> mix;; The power of pattern matching is the ability to concisely match not only actions but also values to patterns of data. Here is an example written in Haskell which illustrates both of these features: map _ [] = [] map f (h : t) = f h : map f t This code defines a function map, 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 speaking always 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. Map-based conditionalsIn programming languages that have associative arrays or comparable data structures, such as Python, Perl, PHP or Objective-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 have anonymous functions or that allow a programmer to assign a named function to a variable reference, conditional flow can be implemented by using a dictionary as a dispatch table. Branch predicationAn alternative to conditional branch instructions is branch predication. Predication is an architectural feature that enables instructions to be conditionally executed instead of modifying the control flow. Choice system cross referenceThis 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.
See also
References
External links
Hidden categories:
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||