Wednesday, September 29, 2010

Implementation Issues Of Functions in C,C++

There are a few important things to remember about functions that affect their
efficiency and usability. These issues are the subject of this section.

Parameters and General-Purpose Functions
A general-purpose function is one that will be used in a variety of situations, perhaps
by many different programmers. Typically, you should not base general-purpose
functions on global data. All of the information a function needs should be passed
to it by its parameters. When this is not possible, you should use static variables.
Besides making your functions general purpose, parameters keep your code
readable and less susceptible to bugs resulting from side effects.

Efficiency
Functions are the building blocks of C/C++ and are crucial to all but the simplest
programs. However, in certain specialized applications, you may need to eliminate
a function and replace it with inline code. Inline code performs the same actions as a
function, but without the overhead associated with a function call. For this reason,
inline code is often used instead of function calls when execution time is critical.
Inline code is faster than a function call for two reasons. First, a CALL instruction
takes time to execute. Second, if there are arguments to pass, these have to be placed
on the stack, which also takes time. For most applications, this very slight increase in
execution time is of no significance. But if it is, remember that each function call uses
time that would be saved if the function's code were placed in line. For example, the
following are two versions of a program that prints the square of the numbers from 1
to 10. The inline version runs faster than the other because the function call adds time.
in line function call
#include <stdio.h> #include <stdio.h>
int sqr(int a);
int main(void) int main(void)
{ {
int x; int x;
for(x=1; x<11; ++x) for(x=1; x<11; ++x)
printf("%d", x*x); printf("%d", sqr(x));
return 0; return 0;
} }
int sqr(int a)
{
return a*a;
}
 
Note : In C++, the concept of inline functions is expanded and formalized. In fact, inline
functions are an important component of the C++ language.

No comments:

Post a Comment