An if statement is a selection statement that allows more than one possible flow of control.
You can optionally specify an else clause on the if statement. If the test expression evaluates to false (or in C, a zero value) and an else clause exists, the statement associated with the else clause runs. If the test expression evaluates to true, the statement following the expression runs and the else clause is ignored.
When if statements are nested and else clauses are present, a given else is associated with the closest preceding if statement within the same block.
A single statement following any selection statements (if, switch) is treated as a compound statement containing the original statement. As a result any variables declared on that statement will be out of scope after the if statement.[1]
Pseudocode[]
Typical syntax is
if criterion1 action1 else if criterion2 action2 else action3
When the purpose of the if statement is to return/assign one of two values depending on the condition, the ternary operator may be useful.
When several if statements are used in a cascade to choose between several options, a Switch Statement might be worth considering as a more readable and maintainable replacement.
Examples[]
Curly bracket programming languages[]
if (expr) { // statement 1 } else { // statement 2 }
expr
must be a condition (see above).
if (false) { // This will never happen! }
for if statements where there is only one option the brackets can be left out.
if(expr) do_this(); else do_that();
where the statement controls how the function exits you can leave out the else too.
if(expr) return do_this(); return do_that();
Ruby[]
var = false if var { print "foobar is y\n" } else { print "foobar is n\n" }
Visual Basic[]
If booleanExpression Then statement1 Else statement2 End If
Python[]
if expr: # statement 1 else: # statement 2
or
if var==1: #Something elif var>4: #Something else: #Something
See Also[]
References[]
- ↑ The if statement. IBM.
|