ini tugas pak yuli yang diberikan kemaren
Conditional (programming)
From Wikipedia, the free encyclopedia
(Redirected from If-then-else)
Jump to: navigation, search
This article is about computer programming; for conditional statements in general, see Logical conditional.
In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.
In imperative programming languages, the term "conditional statement" is usually used, whereas in functional programming, the terms "conditional expression" or "conditional construct" are preferred, because these terms all have distinct meanings.
Although dynamic dispatch is not usually classified as a conditional construct, it is another way to select between alternatives at runtime.
Contents
[hide]
* 1 If-Then(-Else)
o 1.1 Else If parts
o 1.2 If expressions
+ 1.2.1 As a ternary operator
+ 1.2.2 As a function
+ 1.2.3 In Haskell
o 1.3 Arithmetic IF
o 1.4 Object-oriented implementation in Smalltalk
* 2 Case and switch statements
* 3 Pattern matching
* 4 Branch predication
* 5 Choice system cross reference
* 6 See also
* 7 External links
* 8 References
[edit] If-Then(-Else)
The if-then construct (sometimes called if-then-else) is common across many programming languages. Although the syntax varies quite a bit from language to language, the basic structure (in pseudocode form) looks like this: (This example is actually perfectly valid Visual Basic or QuickBASIC syntax.)
If (condition) Then
(statements)
Else
(statements)
End If
When an interpreter finds an If, it expects a boolean condition - for example, x > 0, which means "the variable x contains a number that is greater than zero" - and evaluates that condition. If the condition is true, the statements following the Then are executed. Otherwise, the execution continues in the following branch - either in the Else block (which is usually optional), or if there is no Else branch, then after the End If.
After either branch has been executed, control returns to the point after the End If.
In early programming languages - and in particular, in some dialects of BASIC in the 1980s - an if-then statement could only contain GOTO statements. This led to a hard-to-read style of programming known as spaghetti programming, with programs in this style called spaghetti code. As a result, structured programming, which allowed (virtually) arbitrary statements to be put in statement blocks inside an if statement, gained in popularity, until it became the norm. While it is possible while using only GOTO statements in if-then statements to write programs that are not spaghetti code and are just as well structured and readable as programs written in a structured programming language, structured programming makes this easier and enforces it. Structured if-then-else statements like the example above are one of the key elements of structured programming, and they are present in most popular modern high-level programming languages including VB (all versions including .NET), C and its derivatives (including C++ and C#), Java and JavaScript.
[edit] Else If parts
By using Else If, it is possible to combine several conditions. Only the statements following the first condition that is found to be true will be executed. All other statements will be skipped. The statements of the final Else will be executed if none of the conditions are true. This example is written in the Ada programming language:
if condition then
-- statements;
elseif condition then
-- more statements;
elseif condition then
-- more statements;
...
else condition then
-- other statements;
end if;
elseif, in Ada, is simply syntactic sugar for else followed by if. In Ada, the difference is that only one end if is needed, if one uses elseif instead of else followed by if.
In some other languages, such as C and Java, else if literally just means else followed by if - so no syntactic sugar is needed or provided. This works since when an else is followed by one statement (in this case the if), it doesn't need any braces.
In Python, there is a special keyword elif for this because Python uses indent to indicate structure, so if you only used else and if, then you would need to keep increasing the indent at every condition. In Perl, there is a special keyword elsif for this because braces are required for if and else, so if you only used else and if, then you would need to keep adding braces.
[edit] If expressions
Many languages support if 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 just perform an action).
[edit] As a ternary operator
Main article: ?:
In C and C-like languages conditional expressions take the form of a ternary operator called the conditional expression operator, ?:, which follows this template:
(condition)?(evaluate if condition was true):(evaluate if condition was false)
This means that conditions can be inlined into expressions, unlike with if statements, as shown here using C syntax:
//Invalid
my_variable = if(x > 10) { "foo" } else { "bar" };
//Valid
my_variable = (x > 10)?"foo":"bar";
To accomplish the same as the second (correct) line above, using a standard if/else statement, this would take more than one line of code (under standard layout conventions):
if (x > 10) {
my_variable = 'foo';
}
else {
my_variable = 'bar';
}
[edit] As a function
In Visual Basic and some other languages, a function called IIf 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.
[edit] In Haskell
In Haskell 98, there is only an if expression, no if statement, and the else part is compulsory, as every expression must have some value.[1] Logic that would be expressed with conditionals in other languages is usually expressed with pattern matching in recursive functions.
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 3). It can be written like this: [2]
if' :: Bool -> a -> a -> a
if' True x _ = x
if' False _ y = y
[edit] Arithmetic IF
This section is missing citations or needs footnotes. Please help add inline citations to guard against copyright violations and factual inaccuracies. (May 2007)
Fortran 77 has an "arithmetic if" statement which is halfway between a computed IF and a case statement, based on the trichotomy x < 0, x = 0, x > 0[3]:
IF (e) label1, label2, label3
Where e is any numeric expression (not necessarily an integer); this is equivalent to
IF (e < 0) GOTO label1
IF (e = 0) GOTO label2
IF (e > 0) GOTO label3
Because this arithmetic IF is equivalent to multiple GOTO statements, it is considered to be an unstructured control statement, and should not be used if more structured statements can be used. In practice it has been observed that most arithmetic IF statements referenced the following statement with one or two of the labels.
This was the only conditional control statement in the original implementation of Fortran on the IBM 704 computer. On that computer it could be implemented quite efficiently using instructions such as 'Branch if accumulator negative'.
[edit] Object-oriented implementation in Smalltalk
In contrast to other languages, in Smalltalk the conditional statement is not a language construct but defined in the class Boolean as an abstract method that takes two parameters, both closures. Boolean has two subclasses, True and False, which both define the method, True executing the first closure only, False executing the second closure only.[4]
var := condition
ifTrue: [ 'foo' ]
ifFalse: [ 'bar' ]
[edit] Case and switch statements
Main article: Switch statement
Switch statements (in some languages, case statements) compare a given value with specified constants and take action according to the first constant to match. The example on the left is written in Pascal, and the example on the right is written in C.
Pascal: C:
case someChar of
'a': actionOnA;
'x': actionOnX;
'y','z':actionOnYandZ;
end;
switch (someChar) {
case 'a': actionOnA; break;
case 'x': actionOnX; break;
case 'y':
case 'z': actionOnYandZ; break;
default: actionOnNoMatch;
}
[edit] Pattern matching
Main article: Pattern matching
Pattern matching is a more sophisticated alternative to both if-then-elseif, and the simple case or switch statements mentioned above. It is available in some programming languages such as the ML language family. Here is a simple example written in the O'Caml language:
match fruit with
| "apple" -> cook pie
| "coconut" -> cook dango_mochi
| "banana" -> mix;;
The true power of pattern matching, however, comes from the ability to concisely (a) match on data structure patterns, and (b) bind variables at the same time. 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 not two separate definitions of the function, but rather definitions of what to do in two cases - one case 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 variables. However, it is frequently used as a choice construct in the languages in which it is available.
[edit] Branch predication
Main article: Branch predication
In assembly language, branch predication is a feature of certain CPU instruction sets which permits conditional execution of instructions, without having to perform costly conditional jumps.
[edit] Choice system cross reference
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 language Structured if switch/select case Arithmetic if Pattern matching[1]
then else else-if
Ada Yes Yes Yes Yes No No
C, C++ and C# Yes Yes not needed [2] fall-through, except C# No No
Eiffel Yes Yes Yes Yes No No
F# Yes Yes Yes not needed [3] No Yes
Fortran[clarification needed] Yes Yes Yes Yes Yes No
Java Yes Yes not needed [2] Yes No No
Haskell Yes Yes, required not needed [2] not needed [3] No Yes
Perl Yes Yes Yes Yes No No
PHP Yes Yes Yes fall-through No No
Visual Basic .NET Yes Yes Yes Yes No No
Windows PowerShell Yes Yes Yes fall-through No Yes
1. a This refers to pattern matching as a distinct conditional construct in the programming language - as opposed to mere string pattern matching support, such as regular expression support.
2. a b The often-encountered else if in the C family of languages, and in Haskell, is not a language feature but a set of nested and independent if 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.
3. a In Haskell and F#, a separate constant choice construct is not needed, because the same task can be done with pattern matching.
[edit] See also
Search Wiktionary Look up then or else in Wiktionary, the free dictionary.
* Branch
* Dynamic dispatch for another way to make execution choices
* McCarthy Formalism for history and historical references
[edit] External links
* If Else condition examples an language reference links in many programming languages (JavaScript, Java, PHP, Perl, Python, C, C++, Objective-C, C#, Bash, Pascal, XSLT, Excel, Ruby, Fortran, Velocity)
* Microsoft Excel IF Function
Tidak ada komentar:
Posting Komentar