انت هنا الان : شبكة جامعة بابل > موقع الكلية > نظام التعليم الالكتروني > مشاهدة المحاضرة

Functions in C Plus Plus

الكلية كلية العلوم للبنات     القسم قسم الحاسبات     المرحلة 2
أستاذ المادة مهدي عبد سلمان المسلماوي       3/29/2011 10:03:21 AM

Functions in C++

 

C++ program is a collection of functions written in one file ore more. There is a special function called main function. main function is the starting point for the execution of a program. The definition of main ( ) would look like this:

            int main()

 

            {

 

                        ………// main program statements

 

                        ………

 

                        return (0);

 

            }

 

The returned value, 0, told the operating system that the program is terminated normally, otherwise main that there is a problem in execution of the program.

Any other functions defined in the program can only call from the main () function directly or indirectly via other functions which should be called from the main ().

 

Function Prototype

 

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 prototype a template is always used when declaring and defining a function. When 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.

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 volume(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.

(Declaration tell the program that there is a function will be defined later, if there is a call for it before definition)

In the function definition, names are required because the arguments must be referenced inside the function. Example:

                                    float volume(int a, float b, float c)

 

                                    {

 

                                                float v=a*b*c;

 

                                                …….

 

                                                …….

 

                                                return (v);

 

                                    }

 

The function volume( ) can be invoked in a program as follows:

            Cube1= volume (b1, w1, h1); //function call

The variables b1, w1 and h1 are known as the actual parameters which specify the dimensions of cube1. Their types (which have been declared earlier) should match with the types declared in the prototype.

We can also declare function with empty argument list, as in the following example:

                                                            void disply(void);

 

 

Call by Reference

 

In normal calling(call-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 copies of values.

This mechanism is fine if the function does not need to alter the values of the original variables. 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.

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, int & b)

 

                                    {

 

                                                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) a and b.

 

Return by Reference

 

A function can also return a reference. Consider the following function:

                         int & max(int & x, int & y)

 

                        {

 

                                    if (x>y)

 

                                        return x;

 

                                    else

 

                                        return 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 assign -1 to a if it is larger, otherwise -1 to b.


Inline Functions

 

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. To eliminate the cost of calls to small function, C++ proposes a new feature called inline function.  An inline function is a function that is expanded inline when it is invoked. That is, the complier replaces the function call with the corresponding function code. The inline functions are defined as follows:

                        inline function-header

 

                        {

 

                                    Function body

 

                        }

 

Example:

                        inline double cube(double a)

 

                        {

 

                                    Return(a* a*a);

 

                        }

 

The above inline function can be invoked by statements like

                        c= cube(3.0);

                        d= cube(2.5+1.5);

All inline functions must be defined before they are called. Usually, the functions are made inline when are small enough to be defined in one or two lines. Example:

                        inline double cube(double a){return(a*a*a);}

 

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 containing static variables.

4- If inline functions are recursive.

Inline function makes a program run faster, but it makes a program to take more memory.

///////////////////////////[ INLINE FUNCTIONS ]/////////////////////////

 

#include <iostram.h>

 

#include <stdio.h>

 

inline float mul(float x, float y) // inline FUNCTION

 

{

 

          return(x*y);

 

}

 

inline double div(double p, double q) // inline FUNCTION

 

{

 

         return(p/q);

 

}

 

int main (void )

 

{

 

       float a = 12.345;

 

       float b = 9.82;

 

       cout << mul(a,b) << "\n";

 

       cout << div(a,b) << "\n";

 

}

 

//////////////////////////////<program 4.1>/////////////////////////////

 

The output of program would be

            121.227898

            1.257128

Question:

1. What we are mean by: Function declaration, function definition, function call, call-by-value, call by reference, return by reference?

2. What are the reasons of using of inline functions?

3. What are the situations where the inline functions treated as normal functions?

 


المادة المعروضة اعلاه هي مدخل الى المحاضرة المرفوعة بواسطة استاذ(ة) المادة . وقد تبدو لك غير متكاملة . حيث يضع استاذ المادة في بعض الاحيان فقط الجزء الاول من المحاضرة من اجل الاطلاع على ما ستقوم بتحميله لاحقا . في نظام التعليم الالكتروني نوفر هذه الخدمة لكي نبقيك على اطلاع حول محتوى الملف الذي ستقوم بتحميله .