Sams Teach Yourself C in 21 Days

(singke) #1
Getting More from Functions 523

18


As implemented in this listing, the function half()on lines 38–66 includes no
error checking (for example, if an invalid type argument is passed). This is
because, in a real program, you wouldn’t use a function to perform a task as simple as
dividing a value by two. This is an illustrative example only.
You might think that the need to pass the type of the pointed-to variable would make the
function less flexible. The function would be more general if it didn’t need to know the
type of the pointed-to data object, but that’s not the way C works. You must always cast a
voidpointer to a specific type before you dereference it. By taking this approach, you
write only one function. If you don’t make use of a voidpointer, you need to write four
separate functions—one for each data type.
When you need a function that can deal with different data types, you can often write a
macro to take the place of the function. The example just presented—in which the task
performed by the function is relatively simple—would be a good candidate for a macro.
(Day 21, “Advanced Compiler Use,” covers macros.)

ANALYSIS

DOcast a voidpointer when you use the
value it points to.

DON’Ttry to increment or decrement a
voidpointer.

DO DON’T


Using Functions That Have a Variable Number of Arguments ..........................


You have used several library functions, such as printf()andscanf(), that take a vari-
able number of arguments. You can write your own functions that take a variable argu-
ment list. Programs that have functions with variable argument lists must include the
header file stdarg.h.
When you declare a function that takes a variable argument list, you first list the fixed
parameters—those that are always present (there must be at least one fixed parameter).
You then include an ellipsis (...) at the end of the parameter list to indicate that zero or
more additional arguments are passed to the function. During this discussion, please
remember the distinction between a parameter and an argument, as explained on Day 5,
“Functions: The Basics.”
How does the function know how many arguments have been passed to it on a specific
call? You tell it. One of the fixed parameters informs the function of the total number of
arguments. For example, when you use the printf()function, the number of conversion

29 448201x-CH18 8/13/02 11:14 AM Page 523

Free download pdf