|
|
|
|
|
|
|
Suppose you write a function that doubles whatever input you give it. You would like to be able to pass in an int, a long, a float, or a double. Without function overloading, you would have to create four function names: |
|
|
|
|
|
|
|
|
int DoubleInt(int);
long DoubleLong(long);
float DoubleFloat(float);
double DoubleDouble(double); |
|
|
|
|
|
|
|
|
With function overloading, you make this declaration: |
|
|
|
|
|
|
|
|
int Double(int);
long Double(long);
float Double(float);
double Double(double); |
|
|
|
|
|
|
|
|
This is easier to read and easier to use. You don't have to worry about which one to call; you just pass in a variable, and the right function is called automatically. |
|
|
|
|
|
|
|
|
When you define a function, normally the compiler creates just one set of instructions in memory. When you call the function, execution of the program jumps to those instructions, and when the function returns, execution jumps back to the next line in the calling function. If you call the function 10 times, your program jumps to the same set of instructions each time. This means there is only one copy of the function, not 10. |
|
|
|
|
|
|
|
|
There is some performance overhead in jumping in and out of functions. It turns out that some functions are very small, just a line or two of code. You can gain some efficiency if the program can avoid making these jumps just to execute one or two instructions. When programmers speak of efficiency, they usually mean speed: the program runs faster if the function call can be avoided. |
|
|
|
|
|
|
|
|
If a function is declared with the keyword inline, the compiler does not create a real function: it copies the code from the inline function directly into the calling function. No jump is made; it is just as if you had written the statements of the function right into the calling function. |
|
|
|
|
|
|
|
|
Note that inline functions can bring a heavy cost. If the function is called 10 times, the inline code is copied into the calling functions each of those 10 times. The tiny improvement in speed you might achieve is more than swamped by the increase in size of the executable program. Even the speed increase might be illusory. First, today's optimizing compilers do a terrific job on their own, and there is almost never a big gain from declaring a function inline. More important, the increased size brings its own performance cost. |
|
|
|
|
|