Lesson 18: Introduction to Functions

[spoiler title=”Lesson Video”]
Direct Download of Video (For mobile / offline viewing)(right click > save target as)


[/spoiler]

[spoiler title=”Lesson Source Code”]

[/spoiler]

Homework: Create a function that allows 2 variables to be set to it, multiply them together, output the result, return the outcome to main, add 5 and redisplay the outcome.



What is a function
A function is a section of code that can be called independently from anywhere else in your program to perform a specific task or group of tasks. Functions are able to be passed variables, called “arguments” that are able to be used in the function. These variables are usually passed by “value” (meaning a copy of the variable is made and passed to the function) and in certain cases are passed by reference (meaning the item of the argument itself is passed). Pass by referent will be touched on next lesson, and later on in the series.

Function declarations are broken into 3 parts. The return type, the name, and the argument list.

int addFive (int x). In this example we can see the “int” before addFive. This is the return type. That means that this function is going to put a number where it was called. For example y = x + addFive(x); Would be the same as y = x + (x+5); As long as addFive simply adds 5 to a number and then returns it. The name of this function is addFive, and while function names don’t need to be descriptive, it is important that you assume you won’t be the only person reading your code and that it should be understandable just by reading it. For example if I had the above function named addFive and it added 26, it would be very misleading. The third and final part (int x) in this case is the argument list. What that means is that you are passing in an int as a variable, and when you’re inside the function you can refer to this int as x.

The return type also dictates another piece of code. If you specify anything other than void (return nothing) as a return type, then you need to return a variable / constant of that type.

For example, the following are all valid examples of returning an int.


A few example functions and how you could call them