PROTOTYPES

Examine the file named PROTYPE1.CPP for our first look at a prototype and an illustration of how it is used.

The prototyping used in C++ is no different than that used in ANSI-C. Actually, many C programmers take a rather dim view of prototyping and seem reluctant to use it, but with C++ it is considerably more important and is in much heavier use. In fact, prototyping is required to be used in some situations in C++.

A prototype is a limited model of a more complete entity to come later. In this case, the full function is the complete entity to come later and the prototype is illustrated in line 4. The prototype gives a model of the interface to the function that can be used to check the calls to the function for the proper number of parameters and the correct types of parameters. Each call to the function named do_stuff() must have exactly three parameters or the compiler will give an error message. In addition to the correct number of parameters, the types must be compatible or the compiler will issue an error message. Notice that when the compiler is working on lines 12 and 13, the type checking can be done based on the prototype in line 4 even though the function itself is not yet defined. If the prototype is not given, the number of parameters will not be checked, nor will the types of the parameters be checked. Even if you have the wrong number of parameters, you will get an apparently good compile and link, but the program may do some very strange things when it is executed. To write the prototype, simply copy the header from the function to the beginning of the program and append a semicolon to the end as a signal to the compiler that this is not a function but a prototype. The variable names given in the prototype are optional and act merely as comments to the program reader since they are completely ignored by the compiler. You could replace the variable name wings in line 4 with your first name and there would be no difference in compilation. Of course, the next person that had to read your program would be somewhat baffled with your choice of variable names.

In this case, the two function calls to this function, given in lines 12 and 13, are correct so no error will be listed during compilation.

Even though we wish to use the char type for eyes in the function, we wish to use it as a number rather than as a character. The cast to int in line 20 is required to force the printout of the numerical value rather than an ASCII character. The next example program is similar but without the cast to int.