Sambar Server Documentation
|
CScript Function Definitions |
The function follows a simple algorithm, multiplying the value by itself pow times. A for loop is used to control the number of multiplications, and variable ret_val stores the value to be returned.double power(double val, int pow) { double ret_val = 1.0; unsigned i; for (i = 0; i < pow; i++) ret_val *= val; return(ret_val); }
double power(double val, double pow)
This line begins the function definition. It specifies the type of the
return value, the name of the function, and a list of arguments used by
the function. The arguments are enclosed in brackets and separated by commas.
The body of the function is bounded by a set of curly brackets.
Any variables declared here will be treated as local.
return(ret_val);
On reaching a return statement, control of the program returns to the
calling function. The bracketed value is the value which is returned from the
function. If the final closing curly bracket is reached before any return
value, then the function will return automatically, any return value will
then be meaningless.
You can treat the arguments of a function as variables, however direct manipulation of these arguments won't change the values of the arguments from the calling function. The argument of the called function is just a copy of the calling value. This value is stored in a temporary variable which disappears on return from the function.
Direct changes to the argument variables are confined to the scope of that function. We can solve this problem by passing the addresses of variables to the function. These addresses, or pointers as they are generally known, behave a bit like integer types, except that a limited number of arithmetic operators can be applied to them.
To get back to our original function, we pass it the address of a variable whose value we wish to change. The function then uses the value at that address (or at the end of the pointer). On return from the function, the desired value will have changed. We manipulate the actual value using a copy of the pointer.
Important! The same syntax is used to pass variables by pointer so they can be manipulated by a function. However, in C, to manipulate the pointer location you must use a star (*) to reference the location of the variable in the function. In CScript, knowledge of the variable pointer location is implicit, so regular assignment can be performed.
C function
swap(a, b)
{
c = *b;
*b = *a;
*a = c;
}
a = 1;
b = 2;
swap(&a, &b);
// Result: a == 2, b == 1
CScript function
swap(a, b)
{
c = b; // pointer redirection is implicit
b = a;
a = c;
}
a = 1;
b = 2;
swap(&a, &b);
// Result: a == 2, b == 1
© 2001 Sambar Technologies. All rights reserved. Terms of Use.