DADiSP Developer's Guide > Chapter 2: SPL > Optional Function Arguments

 

Optional Function Arguments

 

A function argument is optional if it is not referenced when the function is invoked.

 

func1(x, y)

{

    if (x < 0)

        return(y);

    else

        return(x);

}

 

func1(1)    returns: 1

func1(-1)   returns: y: Unknown Variable

 

Optional arguments can be tested using the argc variable:

 

optfun(a, b)

{

    /* default b and/or a if not specified */

    if (argc < 2)

    {

        if (argc < 1) a = 1;

 

        b = 10;

    }

 

    return(a * b);

}

 

optfun(2, 3)  returns: 6

optfun(2)     returns: 20

optfun()      returns: 10

 

 

Default Argument Values

 

Arguments can also be assigned default values directly in the argument list:

 

optfun2(a = 1, b = 10)

{

    return(a * b);

}

 

optfun2(2, 3)  returns: 6

optfun2(2)     returns: 20

optfun2()      returns: 10

 

The default value of an argument can be any valid value. Default values can depend on arguments that occur earlier in the argument list.

 

optfun3(a = 10, b = 1..3, c = a * b)

{

    return(a + b + c);

}

 

optfun3()      returns: {21, 32, 43}

optfun3(1)     returns: {3, 5, 7}

optfun3(1, 2)  returns: 5

 

Specifying default argument values in the SPL argument list can greatly simplify the initialization steps of an SPL function.

 

Output Argument Count

 

The outargc variable indicates how many variables will be assigned by a function. For example:

 

outtest(x)

{

    if (outargc > 1)  

    { 

        return(x, x * x)

    } 

    else  

    { 

        return(x)

    } 

}

 

a = outtest(1..100)

(a, b) = outtest(1..100)

 

In both assignments, a is set to the series 1..100, however in the first example, the squared series x*x is not calculated since outargc is 1.

 

outargc allows multi-value functions to be more efficient by testing whether a particular return value even needs to be calculated.