Datasheet

A function declaration is shown below. This example has a return type of void, indicating that the func-
tion does not provide a result to the caller. The caller must provide two arguments for the function to
work with an integer and a character.
void myFunction(int i, char c);
Without an actual definition to match this function declaration, the link stage of the compilation process
will fail because code that makes use of the function
myFunction() will be calling nonexistent code.
The following definition simply prints the values of the two parameters.
void myFunction(int i, char c)
{
std::cout << “the value of i is “ << i << std::endl;
std::cout << “the value of c is “ << c << std::endl;
}
Elsewhere in the program, you can make calls to myFunction() and pass in constants or variables for
the two parameters. Some sample function calls are shown here:
myFunction(8, ‘a’);
myFunction(someInt, ‘b’);
myFunction(5, someChar);
C++ functions can also return a value to the caller. The following function declaration and definition is
for a function that adds two numbers and returns the result.
int addNumbers(int number1, int number2);
int addNumbers(int number1, int number2)
{
int result = number1 + number2;
return (result);
}
Those Are the Basics
At this point, you have reviewed the basic essentials of C++ programming. If this section was a breeze,
skim the next section to make sure that you’re up to speed on the more advanced material. If you
In C++, unlike C, a function that takes no parameters just has an empty parameter
list. It is not necessary to use “void” to indicate that no parameters are taken.
However, you should still use “void” to indicate when no value is returned.
Function declarations are often called “function prototypes” or “signatures” to
emphasize that they represent how the function can be accessed, but not the code
behind it.
17
A Crash Course in C++
04_574841 ch01.qxd 12/15/04 3:39 PM Page 17