If

From LQWiki
Jump to: navigation, search

The if statement is possibly the most basic logical check you can perform. It works by looking at an expression and, depending on the logical outcome of that expression, executes one or more statements.

In its most basic form the if construct looks like this:

IF [ expression ] THEN
  statement - executed if TRUE
ENDIF

So, if 'expression' - whatever it may be - evaluates to a logical TRUE value then the statement is executed. This is useful but can be expanded upon to execute something else if the value is FALSE:

IF [ expression ] THEN
  statement - executed if TRUE
ELSE
  statement - executed if FALSE
ENDIF

Some languages also allow for multiple expressions, thus:

IF [ expression ] THEN
  statement - executed if expression evaluates to TRUE
ELSEIF [ a different expression ] THEN
  statement - executed if a different expression evaluates to TRUE
ELSE
  statement - executed if both expressions above evaluated to FALSE
ENDIF

To demonstrate the concept here is a simple if statement:

IF [ it is raining ] THEN
  take your umbrella
ELSEIF [ it is sunny ]
  take your sunglasses
ELSE
  take nothing
END IF

So, to break it down. If it is raining then I will take my umbrella. If it is NOT raining then I will move on to the next expression, "if it is sunny". If it IS sunny I will take my sunglasses. If neither of the above expressions is true and it is neither raining nor sunny then I won't take anything with me at all!

The most important thing to remember is, each element of an if statement is mutually exclusive - only one will ever be executed. I will never take my umbrella AND my sunglasses at the same time.

This pseudo-code representation of the if statement shows all the elements of the statement you are likely to encounter in the various computer languages that implement it. If anything is ever missing it will most likely be the elseif portion.

To define any further would be to stray into the realms of language definition. Below are some examples and links to get you started.

The Korn Shell Structure

if [ expression ] ;then
  statement(s)
elif
  statement(s)
else
  statement(s)
fi

The C/Perl/Java Structure

if ( expression ) {
  statement(s);
} else {
  statement(s);
}