C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
(ANSI) C. It must be of type int. (However, most compilers—even those that
promote themselves as ANSI C-compatible—enable you to specify void as
main()’s return type.)

One Last Step: Prototype


Making a function work properly involves one last step. If a function returns any value other than
int, you should prototype that function. Actually, you should prototype functions that return integers
as well for clarity.


The word prototype means a model of something else. A prototype of a function is just a model of the
actual function. At first, a C prototype seems like a total waste of time.


The reason functions that return int values don’t need prototypes is that int is the default
prototyped return value unless you specify a different return value. Therefore, these two prototypes
both model the same function:


Click here to view code image


int aFunc(int x, float y); /* 2 passed, one integer returned */

and


Click here to view code image


aFunc(int x, float y); /* 2 passed, one integer returned */

Prototypes aren’t required if you don’t return a value or if you return an integer value, but they are
strongly recommended. When you prototype, C ensures that you don’t pass a float value to a
function that expects to receive a char. Without the prototype, C tries to convert the float to a
char, and a bad value is passed as a result.


To prototype a function, place an exact duplicate of the function’s first line somewhere before
main(). The prototype for gradeAve() appears right before main() in the program you saw
earlier. The line is not a function call because it appears before main(). The line is not a function’s
actual first line because of the semicolon that follows all prototypes. The line is a function prototype.
If your program calls 20 functions, you should have 20 prototypes.


Prototype every function in your programs—every function called by your code and even the built-in
functions such as printf(). “Huh?” might be a good question at this point. You might wonder how
you can prototype printf() when you didn’t write it to begin with. The file stdio.h contains a
prototype for printf(), scanf(), getchar(), and many other input and output functions. The
prototype for strcpy() appears in string.h. You should find out the name of the header file
when you learn a new built-in function so that you can use the #include directive to add the file to
your program and make sure that each function is prototyped.


Tip

main() needs no prototype as long as you place main() as the first function in the
Free download pdf