Functions
A function is a block of code that can be called by name. It can be passed data to operate on (i.e. the parameters) and can optionally return data (the return value).
Functions are an easy way to re-use code and provide an interface to do certain things multiple times. They are essential for every program, as the ability to re-execute statements over and over again, makes them a powerful tool for every program allowing the creation of complex behaviour fairly easily and avoiding ugly or tedious code repetition.
All data that is passed to a function is explicitly passed.
Syntax
Defining a function
Rules for defining a Kipper function:
- A function body/statement must exist.
- An unique identifier must be specified.
- The return type must be specified.
- Arguments are optional for the definition, but all specified arguments must be provided when calling the function.
-
Return statements are optional if the return type is
void
. - The return type must match the type of the return statement.
Calling a function
See also Function call expression.
Behaviour
Functions are executable segments of code that are only executed when their identifier is referenced and called as shown above.
When calling them all arguments have to be passed with the argument types matching. Once the function has been called, the variables are going to be copied to the local function stack (local scope) and be available to the body of the function. This means that the arguments will also be referencable by statements inside the function body.
Important
A function allows for an infinite amount of arguments, though at the current stage of development, no optional or default arguments are available. Meaning all arguments have to be defined when calling a function!
This will likely change in the future, view the roadmap of Kipper for more info.
Function name shadowing
Like many other languages, Kipper allows some form of identifier/variable shadowing, though it's heavily restricted to avoid confusion in many cases. One of the few exceptions to this is the shadowing of the function identifier inside its own scope.
That means that the following code is valid and that the variable x
is
not going to throw an IdentifierError
:
Examples
Simple function
Function with parameters
Function with return value
Function with parameters and return value
X May not call a function without parameters with parameters
X May not call a function without the required parameters
X May not call a function with invalid parameters/types
X May not return a value of a different type than the return type
Documented Function
Remember! It is good to always document your functions.