330 Chapter 14 More on Data Types
For example, assume that the compiler encounters in your program
float x;
y = absoluteValue (x);
Having not previously seen the definition of the absoluteValuefunction, and with
no prototype declaration for it either, the compiler generates code to convert the value
stored inside the floatvariable xto doubleand passes the result to the function.The
compiler also assumes the function returns an int.
If theabsoluteValuefunction is defined inside another source file like this:
float absoluteValue (float x)
{
if ( x < 0.0 )
x = -x;
return x;
}
you’re in trouble. First, the function returns a float,yet the compiler thinks it returns an
int. Second, the function expects to see a floatargument, but you know the compiler
will pass a double.
Remember, the bottom line here is that you should always include prototype declara-
tions for the functions you use.This prevents the compiler from making mistaken
assumptions about return types and argument types.
Now that you have learned more about data types, it’s time to learn about how to
work with programs that can be split into multiple source files. Chapter 15 covers this
topic in detail. Before you start that chapter, try the following exercises to make certain
you understand the concepts you just learned.
Exercises
- Define a type FunctionPtr(using typedef) that represents a pointer to a function
that returns an intand that takes no arguments. Refer to Chapter 11, “Pointers,”
for the details on how to declare a variable of this type. - Write a function called monthNamethat takes as its argument a value of type enum
month(as defined in this chapter) and returns a pointer to a character string con-
taining the name of the month. In this way, you can display the value of an enum
monthvariable with a statement such as:
printf (“%s\n”, monthName (aMonth));