Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
49 views11 pages

Unit 2

funtions

Uploaded by

Rajasekar Mani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
49 views11 pages

Unit 2

funtions

Uploaded by

Rajasekar Mani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 11
FUNCTIONS IN C+ 4.1 INTRODUCTION ‘We know that functions play an important role in C program development. Dividing a program in functions is one of the major principles of top-down, structured programming. Another advantage of using functions is that itis possible to reduce the size of a program’ by calling and using them at dif ferent places in the program, C++ is no exception. Functions continue to be the building blocks of Ce 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 differen tasks depending on the arguments passed to it. Most of these modifications are aimed at meeting the requirements of object-oriented facilities. inthis chapter, we shall briefly discuss the various new features that are added to C-+ functions and their implementation. 4.2 THE MAIN FUNCTION [ANSI-C does not specify any retum type for the main ( ) function which is ing poi C the startin; int for the execution of a program. The definition of main () would look like this: ae main( ) { JImain program statements ‘This is perfectly valid because the main () in ANSI C does not retum any value. In C+, the main () returns a value of type i ; type int to th cit defines main() as matching one ofthe following pate ia Ci ee int main (); int main(int argc, char* argy{ }); The functions that have a return valu fore ¢ should main ( ) function in C++ is, therefore, defined as hie Cae cee forlenaiaate int main () { Feturn(0}; ee ee FUNCTIONS IN C++ 65 tbe return type of functions is int by default, the keyword int in the main ( ) header is option- Most Co+ compilers will generate an error or waming if there is no return statement. Turbo Coe issues the warming Function should return a value and then proceeds to compile the program. It is good programming practice to actually retum a from main ()- Mary operating systems test the retum value (called exit value) to determine if there is any prob- Jem. The normal convention is that an exit value of zero means the program ran successfully, while ‘s nonzero value means there was a problem. The explicit use of a return(0) statement will indicate that the program was successfully executed. 4.3 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 is 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, ANSI 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 dif- ference in prototyping between ANSI 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); | ‘The argument-list contains the types and names of arguments that must be passed to the function. 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, 2); is illegal, lb s netion the names of the arguments are dummy variables and therefore, they are ‘ float volume(int, float, float); Sy) 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 val- ues. 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. 4.6 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 over- heads. Mi 58 OBJECT-ORIENTED PROGRAMMING WITH C++ ion to this problem is to use macro definitions, popularly known as macros, meee taes meenaeaes ‘The major drawback with macros is that they are not really fung. tions and therefore, the usual error checking does not occur during compilation. i 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 function code (something similar to macros expansion). The inline functions are defined as follows: Example: Inline double cube(double a) { return (a *a* a); ‘The above inline function can be invoked by statements like © = cube(3.0); d= cubs(2.5+1.5); On the execution of these statements, the values of ¢ and d will be 27 and 64 respectively. If.the Srpuments 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, Itis easy to make a function inline, All we need to do is to prefix the keyword inline to the fune- tion definition. All inline functions must be defined before they are called - 4, 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 overheed 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: \nline double cube(doubie a) (return (atata):) 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 switeh, or a goto exists, 2. For functions not returning values, if a retum statement existe, 3. If functions contain static variables, 4. If inline functions are recursive. Note: Inline expansion makes a program run faster because return is eliminated. However, it makes the program to take ments that define the inline function are reproduced at each trade-off becomes necessary. the overhead of a function call and up more memory because the state- Point where the function is called. So, 8 FUNCTIONS IN C++ 59 Program 41 illustrates the use of inline functions. TITITTTTLTTTAT TTT TT TU INGINE FUNCTIONS Y/////////// 1/11/1101 finclude #include inline float mul(float x, float y) //inline FUNCTION return(x * y); ! inline double div(double p, double q) //inline FUNCTION return (p/q) ; 1 main() { float a = 12.345; float b = 9.82; cout << mul(a,b) <¢ "\n"; cout <¢ div(a,b) << "\n"; 1 TILUITATTTTTT ATTA TLL T TS PROGRAM &L >SLISLISITTL TTT The output of Program 4.1 would be 121.227898 1.257128 4.7 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 (i.e. function declaration) with default values: 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 float amount(float principal, int period, float ri value = amount(5000, 7); // one argument missing Passes the value of 5000 to principal and 7 to period and then lets the function use default value of 0.15 for rate. The call value = amount (5000, 5, 0.12); // no missing argument Passes an explicit value of 0.12 to rate. A default argument is checked for type at the time of declaration and evaluated at thi time of call. One important point to note is that only the trailing arguments can have default values. That is, we Must add defaults from right to left. We cannot provide a default value to a particular argument in the middle of ari argument list. Some examples of function declaration with default values are: 60 OBJECT-ORIENTED PROGRAMMING WITH C++ int mul(int, intj = 5, int k = 10); ee int mul{int i = 5, intj); Teal int mulfiti=0, int} intk= 10); Hfllega int mulfint i= 2, intj =5, intk= 10); egal Default arguments are useful in situations where some arguments always have the sate Value, Ro, instance, bank interest may remain the same for all customers for a particular Peto of deposit, jy also provides a greater flenbity tthe programmers. A function can be writen with more parang ters than are required for its most common application, Using default arguments, a programmer ca, use only those arguments that are meaningful to a particular situation. Program 4.2 illustrates the use of default arguments. TITTTITTTATTTTALTL TT DEFAULT ARGUMENTS VIII TTA #include #include main() { float amount; float value(float p, int n, float r = 0.15);//prototype void printline(char ch = '*',int len = 40);//prototype printline(); //uses defult values for arguments amount = value(5000.00,5); //default for 3rd argument cout << "\n Final Value = " << amount << "\n\n' printline(' //use default value for 2nd argument +FUNCTION DEFINITIONS. . of p, int n, float r) int year = 1; float sum = p; while(year <= n) { sum = sum * (1+r); year = year + 1; 1 return (sum) ; 1 void printline(char ch, int len) { for(int i = 1; i <= len; i++) pri "So", ch); pereeetenees en; i++) print£("%c",ch); 1 TUTEVELLTTATLTTLT TAT TL PROGRAM 4.2 >/PATLTILIIT ITT LLL ‘The output of Program 4.2 would be: Final Value }0056.786133 Advantages of providing the default arguments are: FUNCTIONS IN C++ 61 1. We can use default arguments to add new parameters to te existing functions. , 'sed to combine similar functions into one. 2, Default arguments can be u! 4:8 const ARGUMENTS In C#+4, an argument to a function can be declared as const as shown below. int strlen(const char *p); int length(const string &s); compiler that the functic when this condition is violated. This ty} ‘The qualifier const tells the ‘on should not modify the argument. The compiler will generate an error wl pe of declaration is signifi- ant only when We pass arguments by reference or pointers. 4.9 FUNCTION OVERLOADING ff the same thing for different purposes. C++ also permits overloading of functions. This means that we can use the same function name to create Fomotions 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 an the argument list inthe function call. ‘The correct function to be invoked is determined by check: ing the number and type of the arguments but not on the function type. For example, an overloaded add( ) function handles different types of data as shown below: ‘As stated earlier, overloading refers to the use o 11 Declarations int add{int a, int b); II prototype 1 int add(int a, int b, int c); I prototype 2 double add(double x, double y);_// prototype 3 double add(int p, double q); II prototype 4 double add(double p, int q); I prototype H Function calls cout << ada(5, 10); //uses prototype 1 cout << add(15, 10.0); // uses prototype 4 cout << add(12.5, 7.5); J/ uses prototype 3 cout << add(5,.10, 15); // uses prototype 2 cout << add(0.75, 5); // uses prototype 5 A functic M1 i ion call first matches the prototype having the same number and type of arguments and then calls the approy ‘ ’ priate function for i . ever eee i Seas A best match must be unique. The function selection 1. The compil ipiler first tries to find ai i ounlrtenee mn exact match in which the types of actual arguments are an exact match is not found, i Pelee und, the compiler uses the integral promotions to the actual char to int float to double to find a match. 2 im oo! 3. When either of them fails, the compiler tries to use the built-in conversions(the implicit assignment conversions) to the actual arguments and then uses the function whose m, is unique. Ifthe conversion is possible to have multiple matches, then the compiler yi generate an error message. Suppose we use the following two functions: long square(long n) double square(double x) A function call such as 62 OBJECT-ORIENTED PROGRAMMING WITH C++ square(10) will cause an error because int argument can be converted to either long or double, thereby creating an ambiguous situation as to which version of square( ) should be used If all of the steps fail, then the compiler will try the user-defined conversions in combina. tion with integral promotions and built-in conversions to find a unique match. User. defined conversions are often used in handling class objects. Program 4,3 illustrates function overloading. JIITITITITTITTIT 11 EUNCTION OVERLOADING VAITITITTTTTT TTT #linclude overload volume;//Needed on early systems int volume (int) ; //Prototype declarations double volume(double, int); //for overloading volume () long volume(long, int, int); main() t cout << volume(10) << "\n"; cout ¢< volume(2.5, 8) << "\n"; cout <¢ volume(100L, 75, 15); s++.+.FUNCTION DEFINTTIONS nt s) return(s * s * s); double volume(double r, int h) ( long volume(long 1, int b, int h) { // cylinder return(3.14519 * r * r * h); // rectangular box return(1 * b * h); 1 PITITITITITTTTTTTITLT ITS PROGRAM 4,3 ITT L FUNCTIONS IN C++ 63 ‘The output of Program 4.3 would be: 1000 157.2595 112500 Overloading of the functions should be done with caution, We should not overload unrelated func- tions and should reserve function overloading for functions that perform closely related tasks. Sometimes, the default arguments may be used instead of overloading. This may reduce the number of functions to be defined. Overloaded functions are extensively used for handling class objects. They will be illustrated later when the classes are discussed. 4.10 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. The friend functions are discussed in Section 5.15 and virtual functions in Section 9.5. REVIEW QUESTIONS AND EXERCISES 4.1 State whether the following statements are TRUE or FALSE. (a) A function argument is a value returned by the function to the calling program. (b) When arguments are passed by value, the function works with the original arguments in the calling program. (©) When a function returns a value, the entire function call can be assigned to a variable. (@) A function can retum a value by reference. (@) When an argument is passed by reference, a temporary variable is created in the calling program to hold the argument value. : (® It is not necessary to specify the variable name in the function prototype. 4.2. What are the advantages of function prototypes in C++? 43. Describe the different styles of writing prototypes. 44_ Find errors, if any, in the following function prototypes. {a) float average(xy); (b) int motint a,b); (6) int display(..); (d) void Vectint” BV, int & size); (6) void printtloat data [], size = 20); 45 Whats the main advantage of passing arguments by reference? 4.6 When will you make a function inline? Why? 4.7. How does an inline function differ from a preprocessor macro ? 4.8 When do we need to use default arguments in a function? 4.9 Whats the significance of an empty parenthesis in a function declaration? 4.10 What do you meant by overloading of a function? When do we use this concept? 4.11 Comment on the following function definitions: (@) int ( int m= 15, } (b) double f0 { HCH 64 OBJECT-ORIENTED PROGRAMMING WIT | retumn(&m); | retur(n); ) 412 Find errors, if any, inthe following function definition for displaying a matrix: Void display(int Af ]{], int m, int n) { forli=0; i

You might also like