if

Last edit

Summary: The else syntactical cocomponent (from markhobley.yi.org)

Added:

> === The else syntactical cocomponent
> The else [[syntactical cocomponent]] may be used as part of an if conditional construct to allow one of two [[branch]]es of code to be conditionally executed depending on the value of a boolean expression.
> {{{
> if (EXPRESSION)
> ACTION;
> else
> ALTERNATIVE ACTION;
> }}}
> The following example shows blocks of code being used within an if and else conditional construct. The code within the first block gets executed if the condition is true, otherwise the code within the second block is executed:
> {{{
> if ($guess == 6)
> print 'Wow! That was a lucky guess!'
> else
> print 'Sorry! Your guess was wrong!'
> }}}


The if [[condition?]]al construct allows a statement or [[block?]] of code to be [[condition?]]ally executed based on the result of a [[boolean?]] expression. The branch within the [[condition?]], only gets executed if the [[expression?]] evaluates to a [[true?]] value. The if [[condition?]] its simplest form is:

if (CONDITION) STATEMENT

For example:

 if (guess == 6) print "Wow! That was a lucky guess."

There are no then or endif cocomponents

Note that the awk extraction and reporting language does not utilize then or endif syntactical cocomponents.

Using squiggly braces to conditionally execute a branch containing more than one statement

In order to [[conditional?]]ly execute more than one statement within a conditional branch, it is necessary to enclose the statements within squiggly braces:

 if (guess == 6) {
   print "Wow! That was a lucky guess."    # Multiple statements in a conditional block
   prize = 30000
 }

The else syntactical cocomponent

The else [[syntactical_cocomponent?]] may be used as part of an if conditional construct to allow one of two branches of code to be conditionally executed depending on the value of a boolean expression.

if (EXPRESSION)
ACTION;
else
ALTERNATIVE ACTION;

The following example shows blocks of code being used within an if and else conditional construct. The code within the first block gets executed if the condition is true, otherwise the code within the second block is executed:

 if ($guess == 6)
   print 'Wow! That was a lucky guess!'
 else
   print 'Sorry! Your guess was wrong!'

Nested conditional constructs

It is possible to created nested conditional structures: