Page 68 - Programming Microcontrollers in C
P. 68
Functions 53
Data returned from a function will always be converted to the
correct type before it is passed back to the program. If you wish to
have a different type returned, the cast operator can be used to change
the return data type to any type desired.
ANSI C defined the type void. This type is used in several dif
ferent ways. If there is no function return, the prototype must identify
the function as type void. Also when there are no function argu
ments, the argument list must contain the type void. This use of the
keyword void will prevent problems in function calls.
Note that the function prototype above is terminated with a semi
colon. The semicolon is needed in the function prototype, but it is
not to be used after the name of the function in the code where the
function is defined. The function prototype is a declaration state
ment that merely provides information to the compiler while the
function prologue, the first line of the function, is a function defini
tion which opens the code for the function.
The philosophy in C is to use functions with little provocation.
Using many functions produces code that is easy to read and follow.
Often it is easier to debug many small functions rather than a larger
program. One must temper these ideas somewhat when writing code
for small microcontrollers. Calling a function requires some over
head that is repeated each time the function is accessed. If the total
overhead is more than the length of the function, it is better to use
in-line code. In-line code implies that the function code is repeated
in-line every time that it is needed. If the function code is much
greater than the calling overhead, the function should be used. In
between these limits, it is difficult to determine a hard-and-fast rule.
In microcontroller applications, it is probably best to use function
calls to a single function if there is a net savings of memory as a
result. This savings is calculated by first determining the code needed
prior to calling the function, the code needed to clean up the process
after the function call, the number of times the function is called, and
the length of the function. The in-line code will be smaller than the
corresponding function code. Therefore, if the total code for the num
ber of function calls listed first exceeds the total in-line code required
to accomplish the same operations, then use the in-line code. Other
wise, use function calls.