7.1 Function Basics
A function is a group of statements that together perform a task. All C programs made up of one or more functions. There must be one and only one main function.
You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division usually is so each function performs a specific task.
A program will be executing statements sequentially inside one function when it encounters a function call.
A function call is an expression that tells the CPU to interrupt the current function and execute another function.
The CPU 'puts a bookmark' at the current point of execution, and then calls (executes) the function named in the function call. When the called function terminates, the CPU goes back to the point it bookmarked, and resumes execution.
Function definition
return_type function_name( parameter list )
{
//statements
}
- The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value.
- function name is the identifier by which the function can be called.
- A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.
- statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.
Example
/* Function returning addition of 2 integers */
int add(int a, int b)
{
int total ;
total= a+b;
return total;
}
7.2 Declaration, call & argument
Function Declaration
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );
For our defined function add() in previous chapter, following is the function declaration:
int add(int a, int b);
Parameter names are not important in function declaration only their type is required, so following is also valid declaration:
int add(int, int);
Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
Function Call
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.
For example:
int main ()
{
int a = 100;
int b = 200;
int ret;
// calling a function to get addition.
ret = add(a, b);
cout << "addition is : " << ret << endl;
return 0;
}
Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.
The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
Call by pointer
This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
Call by reference
This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
7.3 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.
Preceding a function declaration with the inline specifier informs the compiler that inline expansion is preferred over the usual function call mechanism for a specific function. This does not change at all the behavior of a function, but is merely used to suggest the compiler that the code generated by the function body shall be inserted at each point the function is called, instead of being invoked with a regular function call.
For example, the concatenate function above may be declared inline as:
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.
Note that most compilers already optimize code to generate inline functions when they see an opportunity to improve efficiency, even if not explicitly marked with the inline specifier. Therefore, this specifier merely indicates the compiler that inline is preferred for this function, although the compiler is free to not inline it, and optimize otherwise. In C++, optimization is a task delegated to the compiler, which is free to generate any code for as long as the resulting behavior is the one specified by the code.
7.4 Recursion
Recursion is a programming technique that allows the programmer to express operations in terms of themselves.
In C++, this takes the form of a function that calls itself. A useful way to think of recursive functions is to imagine them as a process being performed where one of the instructions is to "repeat the process". This makes it sound very similar to a loop because it repeats the same code, and in some ways it is similar to looping. On the other hand, recursion makes it easier to express ideas in which the result of the recursive call is necessary to complete the task. Of course, it must be possible for the "process" to sometimes be completed without the recursive call.
void CountDown(int nValue)
{
using namespace std;
cout << nValue << endl;
CountDown(nValue-1);
}
int main(void)
{
CountDown(10);
return 0;
}
When CountDown(10) is called, the number 10 is printed, and CountDown(9) is called. CountDown(9) prints 9 and calls CountDown(8). CountDown(8) prints 8 and calls CountDown(7). The sequence of CountDown(n) calling CountDown(n-1) is continually repeated, effectively forming the recursive equivalent of an infinite loop.
This program illustrates the most important point about recursive functions: you must include a termination condition, or they will run “forever” (or until the call stack runs out of memory).
Stopping a recursive function generally involves using an if statement. Here is our function redesigned with a termination condition:
void CountDown(int nValue)
{
using namespace std;
cout << nValue << endl;
// termination condition
if (nValue > 0)
CountDown(nValue-1);
}
int main(void)
{
CountDown(10);
return 0;
}
Now when we run our program, CountDown() will count down to 0 and then stop!

Comments
Post a Comment