Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Conditional (computer programming)
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===If–then–else expressions=== {{See also|Ternary conditional operator}} Many languages support ''conditional expressions'', which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which may not be permitted in the context of a value). The concept of conditional expressions was first developed by [[John McCarthy (computer scientist)|John McCarthy]] during his research into symbolic processing and LISP in the late 1950s. ====Algol family==== [[ALGOL 60]] and some other members of the [[ALGOL]] family allow <code>if–then–else</code> 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: <pre> myvariable := if x > 20 then 1 else 2 </pre> <!-- Don't place a semicolon at the end of the above ALGOL statement. It is NOT C. --> ====Lisp dialects==== Conditional expressions have always been a fundamental part of [[Lisp (programming language)|Lisp]]{{nbsp}}. In pure LISP, the <code>COND</code> function is used. In dialects such as [[Scheme (programming language)|Scheme]], [[Racket (programming language)|Racket]] and [[Common Lisp]]{{nbsp}}: <syntaxhighlight lang="scheme"> ;; Scheme (define (myvariable x) (if (> x 12) 1 2)) ; Assigns 'myvariable' to 1 or 2, depending on the value of 'x' </syntaxhighlight> <syntaxhighlight lang="lisp"> ;; Common Lisp (let ((x 10)) (setq myvariable (if (> x 12) 2 4))) ; Assigns 'myvariable' to 2 </syntaxhighlight> {{See also|McCarthy Formalism}} ====Haskell==== {{Main|Haskell (programming language)}} In [[Haskell (programming language)|Haskell]] 98, there is only an ''if expression'', no ''if statement'', and the <code>else</code> part is compulsory, as every expression must have some value.<ref name="haskell98report">''[http://www.haskell.org/onlinereport/ Haskell 98 Language and Libraries: The Revised Report]''</ref> Logic that would be expressed with conditionals in other languages is usually expressed with [[pattern matching]] in recursive functions. Because Haskell is [[lazy evaluation|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:<ref name="haskell-ifthenelse-proposal">"[http://haskell.org/haskellwiki/If-then-else If-then-else Proposal on HaskellWiki]"</ref> <syntaxhighlight lang="haskell"> if' :: Bool -> a -> a -> a if' True x _ = x if' False _ y = y </syntaxhighlight> ====C-like languages==== [[C (programming language)|C]] and C-like languages have a special [[ternary operator]] ([[?:]]) for conditional expressions with a function that may be described by a template like this: <code>condition ? evaluated-when-true : evaluated-when-false</code> This means that it can be inlined into expressions, unlike if-statements, in C-like languages: <syntaxhighlight lang="c"> my_variable = x > 10 ? "foo" : "bar"; // In C-like languages </syntaxhighlight> which can be compared to the Algol-family if–then–else ''expressions'' (in contrast to a ''statement'') (and similar in Ruby and Scala, among others). To accomplish the same using an if-statement, this would take more than one line of code (under typical layout conventions), and require mentioning "my_variable" twice: <syntaxhighlight lang="c"> if (x > 10) my_variable = "foo"; else my_variable = "bar"; </syntaxhighlight> 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,<ref>{{cite web|url=http://embeddedgurus.com/stack-overflow/2009/02/efficient-c-tips-6-dont-use-the-ternary-operator/ |title=Efficient C Tips #6 – Don't use the ternary operator « Stack Overflow |publisher=Embeddedgurus.com |date=2009-02-18 |access-date=2012-09-07}}</ref> while others argue that concise expressions are easier to read than statements spread over several lines containing repetition. ====[[Small Basic]]==== <syntaxhighlight lang="vbnet"> x = TextWindow.ReadNumber() If (x > 10) Then TextWindow.WriteLine("My variable is named 'foo'.") Else TextWindow.WriteLine("My variable is named 'bar'.") EndIf </syntaxhighlight> First, when the user runs the program, a cursor appears waiting for the reader to type a number. If that number is greater than 10, the text "My variable is named 'foo'." is displayed on the screen. If the number is smaller than 10, then the message "My variable is named 'bar'." is printed on the screen. ====Visual Basic==== {{Main|Visual Basic}} In [[Visual Basic]] and some other languages, a function called <code>[[IIf]]</code> 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==== {{Main|Tcl}} In [[Tcl]] <code>if</code> is not a keyword but a function (in Tcl known as command or <code>proc</code>). For example <syntaxhighlight lang="tcl"> if {$x > 10} { puts "Foo!" } </syntaxhighlight> invokes a function named <code>if</code> 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 the <code>if</code> function receives the condition as a string value and is responsible to evaluate this string as an expression in the callers scope.<ref>{{cite web|title=New Control Structures|url=https://wiki.tcl-lang.org/page/New+Control+Structures|publisher=[[Tcler's wiki]]|access-date=August 21, 2020}}</ref> Such a behavior is possible by using <code>uplevel</code> and <code>expr</code> 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).<ref>{{cite web|title=uplevel manual page|url=https://www.tcl.tk/man/tcl8.6/TclCmd/uplevel.htm|publisher=[[www.tcl.tk]]|access-date=August 21, 2020}}</ref> Because <code>if</code> 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 an empty string if none of the expressions was non-zero and there was no bodyN.<ref>{{cite web|title=if manual page|url=http://www.tcl.tk/man/tcl8.6/TclCmd/if.htm|publisher=[[www.tcl.tk]]|access-date=August 21, 2020}}</ref> ====Rust==== {{Main|Rust (programming language)}} In [[Rust (programming language)|Rust]], <code>if</code> is always an expression. It evaluates to the value of whichever branch is executed, or to the unit type <code>()</code> if no branch is executed. If a branch does not provide a return value, it evaluates to <code>()</code> by default. To ensure the <code>if</code> expression's type is known at compile time, each branch must evaluate to a value of the same type. For this reason, an <code>else</code> branch is effectively compulsory unless the other branches evaluate to <code>()</code>, because an <code>if</code> without an <code>else</code> can always evaluate to <code>()</code> by default.<ref>{{cite web|title=If and if let expressions|url=https://doc.rust-lang.org/reference/expressions/if-expr.html|access-date=November 1, 2020}}</ref> <syntaxhighlight lang="rust"> // Assign my_variable some value, depending on the value of x let my_variable = if x > 20 { 1 } else { 2 }; // This variant will not compile because 1 and () have different types let my_variable = if x > 20 { 1 }; // Values can be omitted when not needed if x > 20 { println!("x is greater than 20"); } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)