Книга: Advanced PIC Microcontroller Projects in C

4.1.1 Function Prototypes

4.1.1 Function Prototypes

If a function is not defined before it is called, the compiler will generate an error message. One way around this problem is to create a function prototype. A function prototype is easily constructed by making a copy of the function’s header and appending a semicolon to it. If the function has parameters, giving names to these parameters is not compulsory, but the data type of the parameters must be defined. An example follows in which a function prototype called Area is declared and the function is expected to have a floating point type parameter:

float Area(float radius);

This function prototype could also be declared as:

float Area(float);

Function prototypes should be declared at the beginning of a program. Function definitions and function calls can then be made at any point in the program.

Example 4.5

Repeat Example 4.4 but declare LowerToUpper as a function prototype.

Solution 4.5

Figure 4.7 shows the program where function LowerToUpper is declared as a function prototype at the beginning of the program. In this example, the actual function definition is written after the main program.

/**********************************************************************
                          LOWERCASE TO UPPERCASE
                        =========================
This program converts the lowercase character in variable Lc to uppercase
and stores in variable Uc.
Programmer: Dogan Ibrahim
File:       LTOUPPER2.C
Date:       May, 2007
************************************************************************/
unsigned char LowerToUpper(unsigned char);
/* Start of main program */
void main() {
 unsigned char Lc, Uc;
 Lc = 'r';
 Uc = LowerToUpper(Lc);
}
/* Function to convert a lower case character to upper case */
unsigned char LowerToUpper(unsigned char c) {
 if (c >= 'a' && c <= 'z') return (c - 0x20);
 else return c;
}


Figure 4.7: Program using function prototype

One important advantage of using function prototypes is that if the function prototype does not match the actual function definition, mikroC will detect this and modify the data types in the function call to match the data types declared in the function prototype. Suppose we have the following code:

unsigned char c = 'A';
unsigned int x = 100;
long Tmp;
long MyFunc(long a, long b); // function prototype
void main() {
 ...............
 ...............
 Tmp = MyFunc(c, x);
 ...............
 ...............
}

In this example, because the function prototype declares the two arguments as long, variables c and x are converted to long before they are used inside function MyFunc.

Оглавление книги


Генерация: 1.632. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз