Here are two versions of the same function; they both return the maximum value between x and y.
This one is more useful for illustrating the possible components of a function. In this first one, we show how to declare a local variable (scope will be discussed shortly).
Example 2 - A more efficient version
This one is more efficient since it doesn't require the local variable z. This second one uses 6 fewer bytes of program memory than the first one – data memory usage is the same. z is temporarily allocated on the stack so no "extra" RAM is required, but more program code is needed to manipulate z.
- The first line of the function is known as the function header. The header contains all of the information about how a program can interface with a function. It lists any parameters that the function will accept, along with their respective data types. It also defines what type of data is returned by the function. In this case, the function will accept two parameters, both of which are integers. Note that we cannot declare the parameters as a list of variables after one data type such as (int x, y) which was perfectly legal to do when declaring ordinary variables. In the header, each parameter variable must be individually listed after its data type. This function also returns an integer value.
- In the first function, we declare a local integer variable z to use within the scope of this function. z is only accessible within this function, as are x and y.
- In both functions, we use the conditional operator ?: to determine which parameter has the largest value. The first function assigns the maximum value to z first, then it returns the value of z to the program that called the function. In the second version of this function, we bypass the need to use a local variable and simply return the value of the expression directly.
Return Data Type
A function'stype must match the type of data in the return expression. A function may have multiple return statements, but only one will be executed and they must all be of the same type
Return Data Type Example
While a function can only return one value via the return statement, you may have multiple return statements that are conditionally executed. In this example, only one of the two return statements will be executed. If a is greater than b, then the first return statement will return the value 1. If a is less than or equal to b, then the second return statement will return the value .
The functiontype is void if
- The return statement has no expression
- The return statement is not present at all
A function's parameters are declared just like ordinary variables, but in a comma delimited list inside the parentheses.
The parameter names declared in the function header are local to the function, meaning that they are not valid anywhere outside of the function.
A parameter list may mix