Function is a code block that executes certain task.
A void function doesn't return any value.
Example:
Output:
Via the return keyword a result can be returned.
Let's have an example in which rectangle's area is calculated by passing arguments about it's sides.
Example:
Output:
There are couple of things to mark:
lines 1 - 2
. It accepts two arguments -
widthArg
and heightArg
.calcRectangleArea
returns a result.calcRectangleArea
is called at line 4
.area
.If a function requires more arguments than the passed ones, an exception is thrown.
The function printArgs
expects 3 arguments but the last one
(c
) is not passed. For that reason an exception is thrown.
Default value may be specified for function parameters.
Let's look at the following:
Output:
At line 5
the function argument is not passed thus it
takes the default value - 3
specified at line 1
.
If arg
didn't have default value (3), then the code would result in exception due to line 5
.
Calling function before it's definition results in exception.
Example:
The line sayHi()
needs to be the last line of the code in order to avoid error.