To create your own functions in C++, you need the following:
- Provide a function definition
- Provide a function prototype
- Call the function
If you're using a library function, the function has already been defined and compiled for you.
Also you can use the standard library header file to provide the prototype.
All that is left to do is call the function properly.
The associated standard header file cstring contains the function prototype for strlen() and several other string related functions. This advance work allows you to use the strlen() function in programs without further worries.
But when you create your own functions, you have to handle all three aspects--defining, prototyping, and calling---yourself.
Here is a short example:
void simple(); // function prototype, before main()
main()
{
using namespace std;
cout << "main() will call the simple() function:\n"; simple(); // function call return 0; } // function definition (after main()) void simple() { using namespace std; cout << "I'm but a simple function.\n"; } Defining a Function You can group functions into two categories: those that don't have return values and those that do. Functions without return values are termed type void functions and have the following general form: void functionName(parameterList) { statement(s) return; // optional } A function with a return value produces a value that it returns to the function that called it. Here is the general form: typeName functionName(parameterList) { statements return value; // value is type cast to type typeName } Functions with return values require that you use a return statement so that the value is returned to the calling function. The value itself, can be a constant, a variable, or a more general expression. The only requirement is that the expression reduce to a value that has, or is convertible to, the typeName type. C++ does place a restriction on what types you can use for a return value: The return value CAN NOT be an ARRAY. Everything else is possible. (Interestingly, even though a C++ function can't return an array directly, it can return an array that is part of a structure or object!) As a programmer, you don't need to know how a function returns a value, but knowing the method might clarify the concept for you. Typically, a function returns a value by copying the return value to a specified CPU register or memory location. Then the calling program examines that location. Both the returning function and the calling function have to agree on the type of data at that location. The function prototype tells the calling program what to expect, and the function definition tells the called program what to return. A function terminates after excecuting a return statement. If a function has more than one return statement--for example, as alternatives to different if else selections--the function terminates after it excecutes the first return statement it reaches. For example, in the folowing example, the else isn't needed, but it does help the casual reader understand the intent: int bigger(int a, int b) { if (a > b)
return a; // if a > b, function terminates here
else
return b; // otherwise, function terminates here
}
Functions with a return value, return a value to the calling program, which can then assign that value to a variable, display the value, or otherwise use it.
Here's a simple example that returns the cube of a type double value:
double cube(double x) // x times x times x
{
return x * x * x; // a type double value
}
For example, the function call cube(1.2) returns the value 1.728. Note that this return statement uses an expression. The function computes the value of the expression(1.728, in this case) and returns the value.
Why Prototypes?
A prototype describes the function interface to the compiler. That is, it tells the compiler what type of return value, if any, the function has, and it tells the compiler the number and type of function arguments. Consider, for example, how a prototype affects this function call:
double volume = cube(side);
First, the prototype tells the compiler that cube() should have one type double argument. If the program fails to provide the argument, prototyping allows the compiler to catch the error. Second, when the cube() function finishes its calculation, it places the return value at some specified location--perhaps in a CPU register, perhaps in memory. Then the calling function main() in this case, retrieves the value from that location. Because the prototype states that cube() is type double, the compiler knows how many bytes to retrieve and how to interpret them. Without that information, the compiler could only guess, and that is something compilers won't do.
Still, you migth wonder, why does the compiler need a prototype? Can't it just look further in the file and see how functions are defined? One problem with that approach is that it is not very efficient. The compiler would have to put compiling main() on hold while searching the rest of the file. An even more serious problem is the fact that the function might not even be in the file. C++ allows you to spread a program over several files, which you can compile independently and then combine later. In such a case, the compiler might not have access to the function code when it's compiling main(). The same is true if the function is part of a library. The only way to avoid using a function prototype is to place the function definition before its first use. That is not always possible. Also, the C++ programming style is to put main() first because it generally provides the structure for the whole program.
Prototype Syntax
A function prototype is a statement, so it MUST have a TERMINATING SEMICOLON. The simplest way to get a prototype is to copy the function header from the function definition and add a semicolon.
double cube(double x); // add ; to header to get prototype
However, the function prototype does NOT require that you provide names for the variables; a list of types is enough.
void cheers(int); // okay to drop variable names in prototype
In general, you can either include or exclude variable names in the argument lists for prototypes. The variable names in the prototype just act as placeholders, so if you do use names, they don't have to match the names in the function definition.
Classic C made prototyping optional, whereas C++ makes prototyping mandatory.
What Prototypes Do for You
They greatly reduce the changes of program errors.
- The compiler correctly handles the return value.
- The compiler checks that you use the correct number of function arguments
- The compiler checks that you use the correct type of arguments. If you don't, it converts the arguments to the correct type, if possible.
C++ automatically converts the value you pass to the type specified in the prototype, provided that both are arithmetic types.
cheers(cube(2));
This code is using two type mismatches in one statement.
First, the program passes the int value of 2 to cube(), which expects a double. The compiler, nothing that the cube() prototype specifies a type double argument, converts 2 to 2.0, a type double value. Then, cube() returns a type double value (8.0) to be used as an argument to cheers(). Again the compiler checks the prototypes and notes that cheers() requires an int. It converts the return value to integer 8. In general, prototyping produces automatic type casts to the expected types.
Prototyping takes place during compile time and is termed static type checking. Static type checking, as you've seen, catches many errors that are much more difficult to catch during runtime.
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten