We’ve seen how to use loops to make the program do the same thing over and over again, but sometimes we want to carry out the same instructions at a later time, not immediately after they’ve just been performed.   In this task there are several roads to cross but they are unevenly spaced, so we can’t use a simple loop to repeat the instructions.   What we need to do is group the instructions for crossing a road together and then tell the compiler at what points that group of instructions needs to be carried out.

We do this with something called a function.   A function is a group of instructions that we give a name to.   Then just by using that name, we can tell the compiler we want that particular group of instructions to be carried out.   When we specify the name of the function and its instructions, we are said to be ‘defining’ the function.   When we give the compiler the name of the function we want to be performed, we are said to be ‘calling’ the function.   A function definition looks like this:

void name()
{
First Instruction
Second Instruction
etc.
}

It might look a little familiar – all the programs we’ve written so far have included a function named void main().   That’s because all programs must have at least one function, and one of those functions must be named ‘main’.   That way, when the program is run the computer knows whereabouts inside the program to start performing the instructions.   Only one function can be named ‘main’ however, or the computer wouldn’t be able to decide which function it was supposed to start at.

The curly brackets might look familiar too.   Just like with the if statement, the else statement, and the while statement, the curly brackets group instructions together so the compiler knows they all belong to the same thing.

Once we’ve defined a function, we can call it from any point within our program.   A ‘function call’ looks like this:

Name();

It’s just the name of the function we want to call, followed by some brackets, and then a semicolon so that the compiler knows that’s the whole statement.

Tasks: