Technology
 

If statement

From Programmer's Wiki

If statements allow different actions to be taken depending on a Boolean expression, or "condition." An if statement consists of a condition and two statements (or "clauses"), commonly known as the then (or if) and else clauses, in that order. The then statement is only executed if the condition is true; otherwise, the else statement is executed if it exists.

Contents

[edit] Typical Use

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.

[edit] Examples

[edit] 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();

[edit] Ruby

var = false
if var {
     print "foobar is y\n" 
}
else { 
   print "foobar is n\n" 
}

[edit] Visual Basic

If booleanExpression Then
   statement1
Else
   statement2
End If

[edit] Python

if expr:
    # statement 1
else:
    # statement 2

or

if var==1:
    #Something
elif var>4:
    #Something
else:
    #Something

[edit] See Also

Control structures
If statement - Switch statement - While loop - For loop - For Each loop - Do while loop
Rate this article: