Conditional Statements

 

The if-else statement is used to make decisions. The syntax is:

 

 if (expression)

       statement1;

 else

       statement2;

 

If expression is non-zero, statement1 is evaluated. If expression is zero, the optional else statement2 is evaluated.

 

For example:

 

if (a < 10) echo(a);

 

if (a < 10) echo(a);

else echo("FALSE");

 

Compound statements must be enclosed in { }.

 

if (a < 10)

{

    b = 1;

    c = 2;

}

else

{

    b = 0;

    c = 0;

}

 

Multiple else-if clauses are supported:

 

if (a < 10)

{

    b = 1;

}

else if (a < 20)

{

    b = 2;

}

else

{

    b = 3;

}

 

The following simple function returns the larger of two numbers:

 

larger(a, b)

{

    local val;

 

    if (a > b)

    {

        val = a;

    }

    else

    {

        val = b;

    }

 

    return(val);

}

 

We can rewrite this function to produce correct results for both scalars and series by employing SPLís series processing capability:

 

larger2(a, b)

{

    return(a*(a >= b) + b*(b > a));

}

 

larger2(1, 10)

 

returns 10

 

larger2({1, 2, 3}, {3, 2, 1})

 

returns the series {3, 2, 3}

 

larger2(2, {1, 2, 3})

 

returns the series {2, 2, 3}

 

 

The C/C++ style ternary conditional statement is also supported. For example, the statement:

 

a = (b > a) ? b : b*b;

 

is equivalent to:

 

if (b > a)

{

    a = b;

}

else

{

    a = b*b;

}

 

The ternary operator allows the larger function to be written more concisely as:

 

larger3(a, b)

{

    return((a >= b) ? a : b);

}

 

 

The C/C++ style switch statement tests an expression against multiple case values:

 

 switch (expression)

 {

      case constant-expression1: statements;

      case constant-expression2: statements;

      default: statements;

 }

 

Unlike C/C++ where the case expression may only assume an integer value, SPL case expressions may be an integer, real or string constants. If a case matches the expression value, execution starts at that case. All case expressions must be different. The optional default case is executed if none of the cases match the expression.

 

myfun(x)

{

    local a;

 

    switch (x)

    {

        case 1:

        case 10:

            a = 0;

            break;

 

        case "line of text":

            a = "string";

            break;

 

        default:

            a = x;

            break;

    }

 

    return(a);

 }

 

 

Function Call

Return Value

myfun(1)

0

myfun("line of text")

"string"

myfun(20)

20

myfun("str")

"str"