C++ tutorial: defining functions


How to define a new function
Defining a new function is very simple; here is the basic format:

return_type function_name (parameters)
	{
	statement1;
	statement2;
	// ... more
	return Value; // (Optional)
	}

Rather than describe the various parts, it will be easier to look at an example. The program chartype.cpp asks the user to press a key, then displays the type of the key pressed: letter, digit, etc. It uses a function called 'CharType' to do the display, given a character variable. Here is part of the CharType function. You should be able to see how it corresponds to the general pattern shown above.

void CharType (char Character)
     {
     // ...
     }

The 'return type' of this function is 'void'. This means that it does not return a value to the calling program. In this case it does not need to: it outputs its reult directly to the screen using 'cout'. The function name is 'CharType'. There is one paramter, called 'Character' of type 'char'. In other words, the calling program will supply this function with one piece of data, a character variable, which will be known as 'Character'. Inside the function, the name 'Character' is used to refer to the piece of data supplied to it. Note that it is up to the programmer to choose sensible names for the functions and their parameters; I could have called the function 'x' and the parameter 'y', but this would not have made it easy to follow.

The one thing missing from the CharType function, which is marked as 'optional' in the basic function format, is a 'return' statement. If a function returns a value to the calling program, it must execute a 'return' statement at the end to indicate what that value is to be. For example, if a function returns a value of type 'float', it might finish with a statement like

     return 99.9;

or

     return Speed;

where 'Speed' is itself a floating point variable.

How to use the new function
Referring again to the program chartype.cpp, you will see in the function 'main' that the 'CharType' function is called:

	cin >> Input;
     CharType (Input);

This section of code asks the user to enter a character, assigns it to the variable 'Input', then passes this data to the 'CharType' function.

Easy, isn't it?
And that's all there is to defining and using simple functions.

©1994-2003 Kevin Boone, all rights reserved