Conditional statement
From Wikipedia, the free encyclopedia
-
This article is about a type of statement in computer programming; for conditional statements in general, see Logical conditional.
In computer science, conditional statements are a vital part of a programming language. These statements are requests to the computer to make an execution choice based on a given condition.
One form is the If-Then clause, sometimes seen as :
If (condition) Then (statements) Else (statements) End If
It works this way - when the computer finds an If (a reserved word), it waits for a data comparison, for example, x = 0 and evaluates the condition. If the condition is true, the statement block following the Then (another reserved word) shall be executed, otherwise the execution shall continue in the following statement block.
Depending on the language, the If may use Then, brackets, and another clause called Else or ElseIf.
There are many other conditional statements in programming languages, however, all of them follow these principles. Other conditional statements include switch statements, case statements and statements with guards.
[edit] Alternative Syntax
Many languages support alternative syntax for if statements: (condition)?true:false.
This is mainly used for in-line if statements that wouldn't be suitable in the place used, for example:
//Invalid $var = if(true) { 'foo' } else { 'bar' }; //Valid $var = (true)?'foo':'bar'
This alternative syntax can also be used inside if statments themselves.
[edit] See also
- Control flow#Choice
- Conditional branch for a theoretical view
- Pattern matching for another way to make execution choices
- Logical conditional for a more general view of conditionals
- Ternary operation for shorthand syntax provided by most programming languages