amibroker

HomeKnowledge Base

A function with multiple return values

A typical AFL function returns one value. For example sin( x ) returns sine value of argument x. Sometimes however it is useful and/or required to return more than one value from the function.

Returning multiple values is possible only via arguments passed by reference, but trouble is that in AFL all arguments are passed by value (as in C language). Passing by value means that only value of variable is passed, not the variable itself, so original variable is not modified as shown in the example below:

function Dummy)
{
    
7// x is treated as function-local
}
//
val 10;
Dummyval );
printf"%g\\n"val ); // will print 10 because 'val' is unaffected by function cal

The behaviour shown above is desirable because we usually want the function to be opaque and do not interfere with what is defined outside of the function except for returning the result of the function.

But what if we actually wanted to write to variables passed as arguments? Well that is possible if we pass the names of the variables as arguments.

// This example shows how to return multiple values
// the idea is to pass the name of the variable instead of
// value
//
function fun_multiple_resultsresult1nameresult2name )
{
  
VarSetresult1name); // setting variable using passed name
  
VarSetresult2name);
  return;
}
//
// to get multiple values from a function
// we call the function passing NAMES of variables
//
10;
20;
printf("a = %g\\n");
printf("b = %g\\n");
//
fun_multiple_results"a""b" ); // pass the names of variables
//
printf("a = %g\\n"); // see new values assigned to variables
printf("b = %g\\n")

Of course we can use arguments passed by name for two-way communication – we can use them as both inputs and outputs as shown in the following example that swaps the values of arguments

function Swapvar1namevar2name )
{
    
temp1 VarGetvar1name ); // read the value from variable
    
temp2 VarGetvar2name );
    
VarSetvar1nametemp2 ); // write the value to variable
    
VarSetvar2nametemp1 );
}
// Initial values
5;
37;
//
printf("Before swap x = %g, y = %g\\n"x);
//
Swap"x""y" ); // pass names of variables
//
printf("After swap x = %g, y = %g\\n"x)

The code above will produce output like this:

Before swap x = 5, y = 37
After swap x = 37, y = 5

So it is clear that variables were passed to the function, swapped and returned successfully.

Comments are closed.