Sunday, 19 August 2012

C++ Programming Tutorial Lesson #7 - Functions


What is a function?

A function is a sub-program that your program can call to perform a task. When you have a piece of code that is repeated often you should put it into a function and call that function instead of repeating the code.

Creating your own function

You declare a function in a similar way as you create the main function. You first put void then the function name and some brackets. The function code goes between curly brackets after that. Here is a function that prints Hello.
void PrintHello()
{
   cout << "Hello\n";
}

Calling your function

Once you have created the function you must call it from the main program. Here is an example of how to call the PrintHello function from above.
void PrintHello()
{
   cout << "Hello\n";
}

void main()
{
   PrintHello();
}

Local and global variables

If you declare a variable inside a function then it is only accessible by that function and is called a local variable. If you declare a variable outside of all functions then it is accessible by any function and is called a global variable.
int g; // Global variable

void MyFunction()
{
   int l; // Local variable
   l = 5;
   g = 7;
}

void main()
{
   g = 3;
}

Parameters

You must use parameters to pass values to a function. Parameters go between the brackets that come after a function. You must choose the datatype of all parameters. We will now create a function that receives a number as a parameter and then prints it.
void PrintNumber(int n)
{
   cout << n;
}

void main()
{
   PrintNumber(5);
}
If you want to pass more than one value then you must separate parameters with a comma.
void PrintNumber(int n, int m)
{
   cout << n << m;
}

void main()
{
   PrintNumber(5, 6);
}
You can either pass a parameter by reference or by value. The default is by value which means that a copy of the variable is made for that function. If you use a * in front of the parameter then you will be passing only a pointer to that variable instead of making another copy of it.
void PrintNumber(int *n)
{
   cout << *n;
}

void main()
{
   int i = 5;
   PrintNumber(&i);
}

Return values

A function can return a value that you can store in a variable. We have been using void in the place of the return variable until now. Here is an example of how to return the number 5 from a function and store it in a variable.
int GetNumber()
{
   return 5;
}

void main()
{
   int i = GetNumber();
}