Sams Teach Yourself C in 21 Days

(singke) #1
Packaging Code in Functions 119

5


You can keep your user-defined functions in a separate source-code file, apart from
main(). This technique is useful with large programs and when you want to use the same
set of functions in more than one program. This technique is discussed on Day 21,
“Advanced Compiler Use.”

Working with Inline Functions ..........................................................................


There is a special type of function that can be created in C. These are inline functions.
Older versions of C will most likely not support inline functions; however, compilers that
support the C-99 standard should have support.
Inline functions are generally small functions. When the compiler executes, it will try to
execute an inline function in the fastest manner possible. This may be done by copying
the function’s code into the calling function. Because execution of this code would be
placed right into the calling function’s code it is called “inline.”
A function is made inline by using the inlinekeyword. The following declares an inline
function called toInches:
inline int toInches( int Feet )
{
return (Feet/12);
}
When the toInches()function is used, the compiler will do its best to optimize it to be
fast. Be aware that although the general assumption is that the code will simply be
moved into the calling function, this is not a guarantee. The only guarantee is that the
compiler will do its best to optimize the use of the code in this function. You will use
inline functions the same way as any other function.

Summary ............................................................................................................


Today’s lesson introduced you to functions, an important part of C programming.
Functions are independent sections of code that perform specific tasks. When your pro-
gram needs a task performed, it calls the function that performs that task. The use of

FIGURE5.6
Place your function
prototypes before your
function definitions.
Generally the proto-
types are near the top
of your listing.

Function call func1(a, b, c);

Function header void func1(int x, int y, int z)

09 448201x-CH05 8/13/02 11:15 AM Page 119

Free download pdf