Functions in c++
Functions in C++
Key Concepts:
➤ Return types in maino
➤ Function prototyping
➤ Call by reference
➤ Call by value
➤ Return by reference
➤ Inline functions
➤ Default argues
➤ Constants arguments
➤ Function overloading
Introduction
We know that functions play an important role in C program development. Dividing a program into functions is one of the major principles of top-down, structured programming. Another advantage of using functions is that it is possible to reduce the size of a program by calling and using them at different places in the program.
Recall that we have used a syntax similar to the following in developing C programs.
void show(); /*Function declaration */
{
show(): /*Function call*/
}
void show() /*Function definition* /
....................
................... /*Function body* /
...................
}
When the function is called, control is trausters to the first statement in the function body. The other statements in the function body are then executed and control returns to the main program when the closing brace is encountered. C++ is no exception. Functions continue to be the building blocks of C++ programs. In fact, C++ has added many new features to functions to make them more reliable and flexible. Like C++ operators, a C++ function can be overloaded to make it perform different tasks depending on the arguments passed to it. Most of these modifications are aimed at meeting the requirements of others oriented facilities. In this chapter, we shall briefly discuss the various new features that are added to C++ functions and their implementation.
The Main Function
C does not specify any return type for the main() function which is the starting point for the execution of a program. The definition of main() would look like this:
main()
{
// main program statements
}
This is perfectly valid because the main() in C does not return any value.
In C++, the main() returns a value of type int to the operating system. C++, therefore, explicitly defines main() as matching one of the following prototypes:
int main();
int main(int argc, char *argv[]);
The functions that have a return value should use the return statement for termination. The main() function in C++ is, therefore, defined as follows:
int main()
{
..............
..............
return 0;
}
Since the return type of functions is int by default, the keyword int in the main() header is optional. Most C++ compilers will generate an error or warning if there is no return statement. Turbo C++ issues the warning.
Function should return a value
and then proceeds to compile the program. It is good programming practice to actually return a value from main().
Many operating systems test the return value (called exit value) to determine if there is any problem. The normal convention is that an exit value of zero means the program ran successfully, while a nonzero value means there was a problem. The explicit use of a return(0) statement will indicate that the program was successfully executed.
Function Prototyping
Function prototyping is one of the major improvements added to C++ functions. The prototype describes the function interface to the compiler by giving details such as the number and type of arguments and the type of return values. With function prototyping, a template in always used when declaring and defining a function. When a function is called, the compiler uses the template to ensure that proper arguments are passed, and the return value is treated correctly. Any violation in matching the arguments or the return types will be caught by the compiler at the time of compilation itself. These checks and controls did not exist in the conventional C functions.
Remember, C also uses prototyping. But it was introduced first in C++ by Stroustrup and the success of this feature inspired the ANSI C committee to adopt it. However, there is a major difference in prototyping between C and C++. While C++ makes the prototyping essential, ANSI C makes it optional, perhaps, to preserve the compatibility with classic C.
Function prototype is a declaration statement in the calling program and is of the following form
type function-name (argument-list);
The argument-list contains the types and names of arguments that must be passed to the function.
Example:
float volume (int x, float y, float z);
Note that each argument variable must be declared independently inside the parentheses
That is, a combined declaration like
float volume(int x, float y, z);
is illegal.
In a function declaration, the names of the arguments are dummy variables and therefore, they are optional. That is, the form
float value(int, float, float);
is acceptable at the place of declaration. At this stage, the compiler only checks for the type of arguments when the function is called.
In general, we can either include or exclude the variable names in the argument list of prototypes. The variable names in the prototype just act as placeholders and, therefore, if names are used, they don't have to match the names used in the function call or function definition. In the function definition, names are required because the arguments must be referenced inside the function.
Example:
float volume(int afloat b.float c)
{
float v= ab*c;
.....................
.....................
}
The function volume) can be invoked in a program as follows:
float double volume(b1,1,h1); // Function call
The variable bl, wl, and hi are known as the actual parameters which specify the dimensions of double. Their types (which have been declared earlier) should match with the types declared in the prototype. Remember, the calling statement should not include type names in the argument list.
We can also declare a function with an empty argument list, as in the following
example:
void display();
In C++, this means that the function does not pass any parameters. It is identical to the statement.
void display(void);
However, in C. an empty parentheses implies any number of arguments. That is, we Thave foregone prototyping. A C++ function can also have an 'open' parameter list by the use of ellipses in the prototype as shown below
void do something(...);
Call by Reference
In traditional C, a function call passes arguments by value. The called function creates a new set of variables and copies the values of arguments into them. The function does not have access to the actual variables in the calling program and can only work on the copies of values. This mechanism is fine if the function does not need to alter the values of the original variables in the calling program. But, there may arise situations where we would like to change the values of variables in the calling program. For example, in bubble sort, we compare two adjacent elements in the list and interchange their values if the first element is greater than the second. If a function is used for bubble sort, then it should be able to alter the values of variables in the calling function, which is not possible if the call-by-value method is used.
Provision of the reference variables in C++ permits us to pass parameters to the functions by reference. When we pass arguments by reference, the formal arguments in the called function become aliases to the 'actual' arguments in the calling function. This means that when the function is working with its own arguments, it is actually working on the original data. Consider the following function:
void swap(int &a &b)// a and b are reference variables
{
int t = a; //Dynamic initialization
a = b;
b = t;
}
Now, if m and n are two integer variables, then the function call
swap(m, n);
will exchange the values of m and n using their aliases (reference variables).
swap(x, y);
Since the return type of max is int &, the function returns reference to x or y (and not the values). Then a function call such as max(a, b) will yield a reference to either a or b depending on their values. This means that this function call can appear on the left-hand side of an assignment statement. That is, the statement
max(a,b) -1;
is legal and assigns -1 to a if it is larger, otherwise -1 to b
Inline Functions
One of the objectives of using functions in a program is to save some memory space, which becomes appreciable when a function is likely to be called many times. However, every time a function is called, it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments into the stack, and returning to the calling function. When a function is small, a substantial percentage of execution time may be spent in such overheads.
One solution to this problem is to use macro definitions, popularly known as macros. Preprocessor macros are popular in C. The major drawback with macros is that they are not really functions and therefore, the usual error checking does not occur during compilation.
C++ has a different solution to this problem. To eliminate the cost of calls to small functions, C++ proposes a new feature called inline function. An inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call with the corresponding function code (something similar to macros expansion).
On the execution of these statements, the values of c and d will be 27 and 64 respectively.
If the arguments are expressions such as 2.5+ 1.5, the function passes the value of the expression, 4 in this case. This makes the inline feature far superior to macros It is easy to make a function inline. All we need to do is to prefix the keyword inline to the function definition. All inline functions must be defined before they are called.
We should exercise care before making a function inline. The speed benefits of inline functions diminish as the function grows in size. At some point the overhead of the function call becomes small compared to the execution of the function, and the benefits of inline functions may be lost. In such cases, the use of normal functions will be more meaningful.
Usually, the functions are made inline when they are small enough to be defined in one or two lines.
Example:
Inline double cube(double a) [return(aaa);}
Remember that the inline keyword merely sends a request, not a command, to the compiler The compiler may ignore this request if the function definition is too long or too complicated and compile the function as a normal function.
Some of the situations where inline expansion may not work are:
1. For functions returning values, if a loop, a switch, or a goto exists.
2. For functions not returning values, if a return statement exists.
3. If functions contain static variables.
4. If inline functions are recursive.
NOTE
Inline expansion makes a program run faster because the overhead of a function call and return is eliminated. However, it makes the program to take up more memory because the statements that define the inline function are reproduced at each point where the function is called. So, a trade-off becomes necessary.
Default Arguments
C++ allows us to call a function without specifying all its arguments. In such cases, the function assigns a default value to the parameter which does not have a matching argument in the function call. Default values are specified when the function is declared. The compiler looks at the prototype to see how many arguments a function uses and alerts the program for possible default values. Here is an example of a prototype (ie. function declaration) with default values:
float ancunt (float principal, int period, float rate-0.15);
The default value is specified in a manner syntactically similar to a variable initialization.
The above prototype declares a default value of 0.15 to the argument rate. A subsequent function call like
value amount (5000,7):
// one argument missing
sees the value of 6000 to principal and 7 to period and then lets the function van default.
const Arguments
In C++, an argument to a function can be declared as const as shown below.
int strlen(const char *p);
int length(const string &s); The qualifier const tells the compiler that the function should not modify the argument. The compiler will generate an error when this condition is violated. This type of declaration is significant only when we pass arguments by reference or pointers.
Function Overloading
As stated earlier, overloading refers to the use of the same thing for different purposes. C++ also permits overloading of functions. This means that we can use the same function name to create functions that perform a variety of different tasks. This is known as function polymorphism in OOP.
Using the concept of function overloading: we can design a family of functions with one function name but with different argument lists. The function would perform different operations depending on the argument list in the function call. The correct function to be invoked is determined by checking the number and type of the arguments but not on the function type.
Friend and Virtual Functions
C++ introduces two new types of functions, namely, friend function and virtual function.
They are basically introduced to handle some specific tasks related to class objects. Therefore, discussions on these functions have been reserved until after the class objects are discussed.
Math Library Functions
The standard C++ supports many math functions that can be used for performing certain commonly used calculations. Most frequently used math library functions are summarized in Table 4.1.
NOTE
The argument variables x and y are of type double and all the functions return the data type double.
To use the math library functions, we must include the header file math.h in conventional C++ and emath in ANSI C++.
SUMMARY
1. It is possible to reduce the size of program by calling and using functions at different places in the program.
2. In C++ the main() returns a value of type int to the operating system. Since the return type of functions is int by default, the keyword int in the main() header is optional.. Most C++ compilers issue a warning, if there is no return statement.
3. Function prototyping gives the compiler the details about the functions such as the number and types of arguments and the type of return values.
4. Reference variables in C++ permit us to pass parameters to the functions by reference. A function can also return a reference to a variable.
5. When a function is declared inline the compiler replaces the function call with the respective function code. Normally, a small size function is made as inline. The compiler may ignore the inline declaration if the function declaration is too long or too complicated and hence compile the function as a normal function.
6. C++ allows us to assign default values to the function parameters when the function is declared. In such a case we can call a function without specifying all its arguments. The defaults are always added from right to left.
7. In C++, an argument to a function can be declared as const, indicating that the function should not modify the argument.
8. C++ allows function overloading. That is, we can have more than one function with the same name in our program. The compiler matches the function call with the exact function code by checking the number and type of the arguments.
9. C++ supports two new types of functions, namely friend functions and virtual functions. Many mathematical computations can be carried out using the library functions supported by the C++ standard library.
Copyrighted material


Comments
Post a Comment