NAME

functions - how to write a function

SYNTAX

modifier type function_name (argument_specification)
{
/* function body */
}

DESCRIPTION

A function is basically a piece of code which takes some data does some things, and hands some data back. Data sent to a a function is called an 'argument'.

This defines a function called 'function_name' returning the type 'type'. The argument_specification is a comma separated list of arguments. Each argument is specified with a type, whitespace and the name of the argument. The last argument may have ... before the name to indicate that that argument shall contain an array of the rest of the arguments given by the caller. Note that using ... automatically makes an the variable an array, so writing

int foo(int * ... ints);

means that 'ints' is an array of arrays of integers. Which might not be what you want.

The modifiers can be zero or more of: static, no_mask, varargs, inline and private. Varargs means that it is ok to call the function with less arguments that would otherwise be needed. Inline means that the function may be inlined in other code. Inline also makes the function no_mask. Static means that the function can not be called from other objects. Private means that the function can not be accessed from programs that inherits this program.

Some times you need to use a function before it is defined, then you can write a 'forward declaration' of the function. This is done by copying the function definition up until (but not including) the '{' and putting a semicolon after it. The forward declaration should be put before the use of the function of course.

Function definitions and forward declarations are toplevel constructs, they can not be written inside functions or expressions.

EXAMPLES

/* Forward declare foobar as taking an array of int as argument
*and returning an int
*/
static int foobar(int *a);

/* This function takes a format string and any number of integers

* as argument and returns a string
*/
string dofobar(string format ,int ... rest)
{
return sprintf(format, foobar(rest));
}

/* Define foobar */
static int foobar(int *a)
{

int e, ret;
ret=1;

for(e=0;e<sizeof(a);e++)
ret*=a[e];

return ret;
}

KEYWORDS

lpc

SEE ALSO

lambda, return and modifier