Folder101   Home Notes Quiz Assigns Info  
Forum Forum
101 Home 101
 
  C++ Level 2

Organizing Code in Functions

Introduction

Functions

Creating a Function

Function Definition

Function Prototype

Header Files

Parameters and Return Values

Passing Parameters

Return Values

Extension Work


  Introduction

So far you have written all of your code inside a function called main. This is acceptable for extremely small programs, but not for large programs because it becomes difficult to understand the code. Moreover, putting everything in main makes it difficult to organize your code properly and control the flow of your program, which can leads to errors in your code.

So, now it is time to learn about functions.


  Functions

What is a Function? In effect, a function is a self-contained block of code - like a subprogram - that can be called upon to execute when convenient. Placing code inside separate functions is extremely useful for breaking down a complicated task into smaller simpler tasks; for organizing and subdividing your program into smaller blocks of code, each blocks designed to do a particular thing.

Lets have an example:-

 

#include <iostream.h>
int getInput(void);
//function prototype

void main()
{
   getInput();

   cout << "The code in getInput will execute before this line";
}

int getInput(void)
{
   char name[80];
   cout <<
"Enter your name" << endl;
   cin >> name
;
   return 0;
}

Here we have two functions, main and getInput. C++ always executes the code inside main first by default. However, the line inside main that says getInput, causes execution to branch out to the getInput function. When all the code in that function has finished executing, execution will return to main and continue to execute any lines following the getInput line.

I always imagine this as popping out to do another task and then coming back to finish off an earlier task.

Note: When you type in the name of a function, this is known as calling a function. When a function has finished executing, we say the function returns.

    Creating a Function

There are two types of functions. New functions you create yourself and pre-defined functions that have already been written, which you can use within your program. In this tutorial we shall be concentrating on creating new functions.

There are two parts to creating a function:-

  1. the function definition

  2. the function prototype

    Function Definition

The function definition contains a function header and the function body. Here is the function definition for the getInput function:-

int getInput(void)

{
   char name[80];
   cout <<
"Enter your name" << endl;
   cin >> name
;
   return 0;
}

Function Header

start of Function Body... ...
...
...
...

... end of Function Body

The function header consists of the name, return type, and parameters. Don't worry, these terms will become clear. In this function the name is getInput, the return type is int and there are no parameters, that's what void means. The function body contains the code.

    Function Prototype

When creating a function, you must declare it, just like you would declare other things, such as integers and floats. In fact, you cannot call a function that hasn't first been declared. This declaration of a function is called a function prototype.

Here is the prototype for my getInput function.

int getInput(void);

All I am doing here is telling the compiler the name, return type, and parameters of the function. In fact, the prototype is identical to the function header, except there is a semicolon on the end. Notice how the prototype and declaration match apart from that semi-colon. You will get a compiler error message if they don't match.

    Header Files

There is one last niggling thing. Where do you type in the function prototype? There are two sensible possibilities:-

  • At the top of the file in which the function definition is.
  • In another file, then use the #include directive to include that file in you program
For now, we will be declaring the prototype at the top of the file in which the function is, but later on the prototypes will be placed in .H header files.

Don't Forget: --  there are two parts to creating a function, the definition and the prototype.


  Parameters and Return Values

We shall be looking in more detail at functions later in the course, however, you need to know a little bit about parameters and return values. To illustrate these ideas, lets create a simple adding and subtracting program with two functions.

Step 1- Create a New Project

Open a new project in VC++. Name your project something like arithmetic. Ensure you have added a source code file in your project. You can save that as arithmeticSource.cpp if you like.

Step 2- Type in the code

Here is part of the program with a function for adding two numbers. You will be expected to create a subtraction function. Copy the code shown below into your program. Be careful with syntax errors.

 

#include <iostream.h>
int add(int a, int b);
//function prototype

void main()
{
   int x, y, z;
   cout << "Enter a whole number" << endl;
   cin >> x;
   cout << "Enter another whole number" << endl;
   
cin >> y;
   
z = add(x, y);

   cout << x << " plus " << y << " equals " << z << endl;
}

int add(int a, int b)
{
   return a + b;
}

Step 3 - Compile, Link and Run

Select Build or Run from the menu to compile, link and run the program. If there are any error messages from the compiler then fix them.

Now that you have tried out your new program, lets examine the code in more detail by starting with the concept of parameters.

    Passing Parameters

C++ program always begins its execution with the main function. So we will begin there.

We can see how the main function begins by declaring the variable x, y and z. After the user is asked to enter some numbers and we catch the inputs in the variables x and y, the function add is called:-

z = add(x, y);

Now the, function prototype for add is:-

int add(int a, int b);

The function contains two arguments inside the parentheses; int a and int b.

What this means is, that when you call the function, it expects you to send it two integer values because it needs those values to make the code inside the body work properly. Moreover, whatever values you pass to the function, it is going to call those values a and b respectively. Passing values to a function is called passing parameters.

In this case, when the function was called it was passed the values of the two parameters x and y. I.e.

z = add(x, y);

Inside the function, a and b are given the same values as x and y.

    Return Value

Inside the add function there is only one line of code:-

return a + b;

The a + b part just adds the two numbers together. The return part returns the results of the addition back to the function that called it, in this case the main function.

When a function returns a value, this means we can catch that value and store it in a variable if we like. In this program, the return value is stored in the variable z, since we have:-

z = add(x, y);

The value of z is then output to the user:-

cout << x << " plus " << y << " equals " << z << endl;

Note: Every function has a return type. If you do not specify a return type, it will be int by default. If a function does not return a value, its return type will be void. Usually you put the return statement at the end of the function, although return statements can legally appear anywhere in the body of the function.


  Extension Work

Carry out the following exercises:-

  1. Complete the arithmetic program by adding another function for subtracting two numbers. Anyone who finds that easy could add multiplication and division functions. You would have to think about changing some of the variables from integers to floats though.

  2. Now start step5 of the practice assignment 3

Thats it!
Now try the quiz questions.