Menu
C++ Tutorials

C++

Functions



Tutorials > C++ > Functions

View Full Source

What are functions?

A function is a sub-program that can be written for use in places where a certain action needs to be taken more than once. This prevents copying and pasting of code and it allows for dynamic programs.
Functions also allow your code to be more modular, allowing greater ease in understanding the workings of your code.

How are functions defined?

Functions take the form :

    return type function name(parameters) { statements }

A return value can be any value that you want to return back from a function. This is usually a value that is computed within the function.
Parameters allow extra information to be passed onto a function. This will be dealt with in the next tutorial.
An example of a function is the main function.

Contents of main.cpp :


#include <iostream>
#include <stdlib.h>

using namespace std;

Our first function is a function named sayHello. It does not return a value and therefore the keyword void is used.
All this function does is print out the string Hello.

void sayHello()
{
	cout << "Hello" << endl;
}

A function always needs to be declared before it can be used. Our functions are being used within our main method. If we want to declare a function at the end of the source file, we need to let the main method know that another function exists.
We therefore have just a function declaration followed by a ; to show that a function with this signature will eventually be defined.

void sayGoodbye();

When calling a function, you use the following :

    function name(parameters);

Our code therefore executes the function sayHello and then the function sayGoodbye. We will see how the function sayGoodbye works soon. The sayGoodbye function can be called as we declared it above.

int main()
{
	sayHello();
	sayGoodbye();

	system("pause");

	return 0;
}

We can now define what our function does. In our example, all it does is print the string Goodbye.

void sayGoodbye()
{
	cout << "Goodbye" << endl;
}

You should now be able to create basic functions that contain no parameters. This should make your programs more readable and modular.

Please let me know of any comments you may have : Contact Me

Source Files : Visual Studio Dev-C++ Unix / Linux

< Tutorial 19 - Scope Tutorial 21 - Function Parameters >

Back to Top


All Rights Reserved, © Zeus Communication, Multimedia & Development 2004-2005

Read the Disclaimer

Links