inline function
Calling a function generally causes a certain overhead (stacking arguments, jumps, etc...), and thus for very short functions, it may be more efficient to simply insert the code of the function where it is called, instead of performing the process of formally calling a function.
inline string concatenate (const string& a, const string& b)
{
return a+b;
}
This informs the compiler that when concatenate
is called, the program prefers the function to be expanded inline, instead of performing a regular call. inline
is only specified in the function declaration, not when it is called.
C ++内联函数提供了另一种选择。使用inline关键字,编译器将函数调用语句替换为函数代码本身(称为扩展的过程),然后编译整个代码。因此,使用内联函数,编译器不必跳转到另一个位置来执行该函数,然后跳回。因为被调用函数的代码已经可用于调用程序。
-------------------------------------------------------------------------------------------------------------------------------
Declaring functions
The prototype of a function can be declared without actually defining the function completely, giving just enough details to allow the types involved in a function call to be known. Naturally, the function shall be defined somewhere else, like later in the code. But at least, once declared like this, it can already be called.
The declaration shall include all types involved (the return type and the type of its arguments), using the same syntax as used in the definition of the function, but replacing the body of the function (the block of statements) with an ending semicolon.
// declaring functions prototypes
#include <iostream>
using namespace std;
void odd (int x);
void even (int x);
int main()
{
int i;
do {
cout << "Please, enter number (0 to exit): ";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}
void odd (int x)
{
if ((x%2)!=0) cout << "It is odd.\n";
else even (x);
}
void even (int x)
{
if ((x%2)==0) cout << "It is even.\n";
else odd (x);
}
Output:
Please, enter number (0 to exit): 9
It is odd.
Please, enter number (0 to exit): 6
It is even.
Please, enter number (0 to exit): 1030
It is even.
Please, enter number (0 to exit): 0
It is even.
---------------------------------------------------------------------------------------------------------------------------------
Recursivity
// factorial calculator
#include <iostream>
using namespace std;
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return 1;
}
int main ()
{
long number = 9;
cout << number << "! = " << factorial (number);
return 0;
}
Recursivity is the property that functions have to be called by themselves. It is useful for some tasks, such as sorting elements, or calculating the factorial of numbers. For example, in order to obtain the factorial of a number (n!
) the mathematical formula would be: