89 of 208
ZBasic Language Reference 81 ZX Microcontroller Family Sub Main() Call foo(3) Call foo(3, 5) End Sub Sub foo(ByVal size as Byte, ByVal cnt as Byte = 1) End Sub If any parameter has a default value specified, all parameters following that parameter must also have a default value. Also, only parameters that are passed ByVal may have a default value. Some parameter types, like arrays and structures for example, are always passed ByRef even if they are defined as ByVal and therefore cannot have a default value specification. 3.19 Subroutine and Function Overloads Overloading is the computer science term for defining two or more procedures having the same name but having different formal parameter lists. The compiler selects which of the overloads to invoke based on the actual parameters specified in a particular call. Several of the ZBasic System Library procedures have multiple overloads (e.g. GetADC()) and you may optionally defined overloads in your own application code. Normally, the compiler will disallow the definition of multiple subroutines/functions with the same name. If you wish to use this capability in your application, you must specifically enable it. This can be achieved by using the directive Option Overload in the first module compiled. Alternately, the compiler option – -overload has the same effect; it must occur on the command line or in the .pjt file before the first .bas file processed. It is important to note that subroutine/function overloading is automatically enabled if ZBasic object-oriented extensions are enabled. See Chapter 4 for more information on the object- oriented extensions. As mentioned earlier, the compiler determines which of several identically named procedures to invoke depending on the number and types of the parameters given in each particular instance. The procedure name along with the types and passing method of the parameters (if any) is referred to as the procedure’s “signature”. If the compiler cannot find a procedure with a signature compatible with a particular invocation, it will generate an error message to that effect. Likewise, if there is more than one procedure whose signature is compatible with a particular invocation, the compiler will issue an error message indicating an ambiguous refererence and enumerating the possible matches. It is important to note that the fact that a procedure is a subroutine or a function is not part of the signature. Moreover, a function’s return type is not part of the signature, either. This means that it is not permissible to create both a function and a subroutine with the same name and parameter list nor it is permissible to create two functions that differ only in return type. Example Option Overload ' enable overloading Sub foo(ByVal x as Integer) Debug.Print "foo ByVal" End Sub Sub foo(ByRef x as Integer) Debug.Print "foo ByRef" End Sub Sub foo(ByVal s as String) Debug.Print "foo string" End Sub