Variable argument lists, Returning values and parameters – Crunch CRiSP File Editor 6 User Manual

Page 20

Advertising
background image

Page 20

Variable argument lists

CRiSP supports a variety of mechanisms which allow for variable numbers of arguments to be passed to
macros. As described above the get_parm() and put_parm() primitives are used to access arguments to
macros. A useful addition to these primitives is the arg_list() primitive. This primitive returns a list
representing the arguments passed to the calling macro. This list can then normally be used as an argument
to further macros to allow for the fact that the called macro may have been passed an arbitrary number of
arguments.

In order to understand this clearly, let's take an example. Suppose we wish to write a macro which acts as a
wrapper around an existing primitive, e.g. the insert() primitive. The insert() primitive is used to insert text
strings into the current buffer. It can take an indefinite number of arguments, the first of which can optionally
be a printf-like formatting string. We could use the arg_list() macro like this:

example()
{

my_insert("hello %s", "world");
my_insert("%d+%d=%d", 1, 1, 1+1);

}
/* Our function -- note no arguments are specified */
/* in the definition. */
my_insert()
{

insert("[");
insert(arg_list());
insert("]");

}

In this example we access the variable number of arguments using arg_list() and thus pass on the
arguments to the insert() primitive without needing to write any macro code to get at and pass on the
arguments.

{button See Also, ALink(crunch,,,)}

Returning values and parameters

There are two ways to return values from a function: you can return a value as the result of the function, or
you can modify one or more of the calling parameters (as in pass by reference).

Returning values

To return a value, use the return statement. Functions can be declared as void, indicating that no value is
to be returned (i.e. the function is procedural). In which case, the return statement takes no argument.
Falling off the end of the function is the same as executing a return statement with no value:

void print_message(string str)

{

printf("%s\n", str);

}

int add2(int a, int b)

{

return a + b;

}

CRiSP also supports an older archaic function, returns, which acts like a function call and arranges a value
to be returned when the function exits. This function should be avoided where possible as it is not
guaranteed to work if any other function or primitive is called after it. This is present for backwards
compatibility only.

Pass by reference

Returning a value from a function using return probably accounts for 99% of the parameter passing
mechanisms used in the CRiSP macros. The alternative way to return values is pass by reference. The
syntax for this is:

void get_max(int a, int b, int c, int& d)

Advertising