Programmer's Wiki

If statement

407pages on
this wiki
Add New Page
Talk0 Share

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 Edit

Typical syntax is

 if criterion1
    if criterion2

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 Edit

Curly bracket programming languages Edit

 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.


where the statement controls how the function exits you can leave out the else too.

   return do_this();

return do_that();

Ruby Edit

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

Visual Basic Edit

If booleanExpression Then
End If

Python Edit

if expr:
    # statement 1
    # statement 2


if var==1:
elif var>4:

See Also Edit

References Edit

Control structures
If statement - Switch statement - While loop - For loop - Foreach loop - Do while loop

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.