Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

Program Flow 31 Declaring Functions When you call a function, the compiler needs to know the types of the function's argu- ments and return value. It uses this information to set up the communication between the function and its caller. If the code for the function comes before the function call (in the source code file), you don't have to do anything else. If the function is coded after the function call or in a different file, you must declare the function before you use it. A function declaration repeats the first line of the function, with a semicolon added at the end: void printSalesTax ( float purchasePrice, float taxRate ); It is a common practice to put function declarations in a header file. The header file is then included (see the next section) in any file that uses the function. Note Forgetting to declare functions can lead to insidious errors. If you call a function that is coded in another file (or in the same file after the function call), and you don't declare the function, neither the compiler nor the linker will complain. But the function will receive garbage for any floating-point argument and return garbage if the function's return type is floating-point. Preprocessor When C (and Objective-C) code files are compiled, they are first sent through an initial program, called the preprocessor, before being sent to the compiler proper. Lines that begin with a # character are directives to the preprocessor. Using preprocessor directives you can: Import the text of a file into one or more other files at a specified point. Created defined constants. Conditionally compile code (compile or omit statement blocks depending on a condition). n n n Including Files The following line: #include "HeaderFile.h" causes the preprocessor to insert the text of the file HeaderFile.h into the file being com- piled at the point of the #include line. The effect is the same as if you had used a text editor to copy and paste the text from HeaderFile.h into the file being compiled. If the included filename is enclosed in quotations ("") : #include "HeaderFile.h" the preprocessor will look for HeaderFile.h in the same directory as the file being com- piled, then in a list of locations that you can supply as arguments to the compiler, and finally in a series of system locations.