Next: Control statements, Previous: Variables and function/procedure names, Up: Syntax [Contents][Index]
Sub-programs can be written as functions or procedures. The only difference between functions and procedures is that functions must return a value while procedures must not return a value. The type of a sub-program which returns a value using the return~<expression> statement becomes func. If return is not used, or is used without an expression, the type becomes proc. The type of the sub-program therefore need not be declared. It is an error to use a procedure in an expression or pass a procedure as an argument to another sub-program where a function should have been passed.
A function or procedure declaration begins with a variable name followed by an argument list. The argument list is enclosed by a round bracket pair ('(' and ')'). A '()' specifies an empty argument list. The function body is in enclosed between the '{' and '}' brackets. E.g.
>/* An example of a function declaration */ >f() { return sin(PI/2); } >/* An example of a procedure declaration */ >p() {print "Value of f() = ",f(),"\n";} >f() 1.00000 >p() Value of f() = 1.00000
A sub-program can be passed as an argument to another sub-program. An argument corresponding to a sub-program can be specified using the func (for a function) or proc (for a procedure) directive. E.g.
>f(x) { return sin(x); } >p(func fa,x) {print "The value of f(",x%5.2f,") =",fa(x),"\n";} >p(f,10) The value of f(10.00) = -0.54402
All symbols (variables, functions, procedures) used in the sub-program code must be either global variables declared before the sub-program declaration or must be one of the argument list. Temporary variables, the scope of which is within the sub-program only, can be declared using the auto directive. E.g.
>f(x) { return sin(x); } >p(func fa,x) { auto t; t=fa(x); print "The value of f(",x%5.2f,") =",t,"\n"; } >p(f,10) The value of f(10.00) = -0.54402
Next: Control statements, Previous: Variables and function/procedure names, Up: Syntax [Contents][Index]