0% found this document useful (0 votes)
5 views

Functions

Unit 3 covers functions in programming, detailing their structure, including the main function, function prototypes, declarations, definitions, and various types of function calls such as call by reference and return by reference. It also discusses advanced concepts like inline functions, default arguments, and function overloading. The unit aims to equip learners with a comprehensive understanding of functions and their significance in structured programming.

Uploaded by

Heureuse
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)
5 views

Functions

Unit 3 covers functions in programming, detailing their structure, including the main function, function prototypes, declarations, definitions, and various types of function calls such as call by reference and return by reference. It also discusses advanced concepts like inline functions, default arguments, and function overloading. The unit aims to equip learners with a comprehensive understanding of functions and their significance in structured programming.

Uploaded by

Heureuse
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/ 18
Unit 3: Functions Notes Structure 3.1 Introduction 3.2. The Main Function 2.3 Funetion Prototype 2.4 The Function Declaration 35 Calling the Funetion 351 The Function Definition 352 Eliminating the Declaration 36 Call by reference 37 Return by reference 38 Inline Functions 39 Default Arguments 3.10. Const arguments 3.11 Function overloading 3.42 Friend function 3.13 Virtual function 314 Summary 3.48 Chock Your Progress 3.16 Questions and Exercises S47 Key Terms 3.18 Further Readings Objectives ‘After studying this unit, you should be able to # Understand the function + Loam about arguments + Understand about reference variable end arguments # Learn about function overloading 3.1 Introduction ‘A function aroups a number of program statements into a unit and gives it a name. This unit can then be invoked fram other parts of the program Functions play an important role in program development. Dividing a program into functions is one of the major principles of structured programming. Another use of functions is that they reduce the size of a program by calling and using them at diferent places in the program. Any sequence of instructions thet appears in a program more than once is @ candidate for being made into a function. The function's code is stored once in the memory, even though it is executed many times in the course of the program. Functions 3.2 The Main Function ‘The main () function is the starting point for the execution of a program, In G++, the main() retums @ value of type int to the operating system. The {functions that have a return value should use the retum statement for termination. The main() function in C+ i, therefore, defined as follows int maia() (os Since the retum type of function is int by default, the keybord int in the main() header is optional, But it is good programming practice to actually return a value from main() An exit value of zero mean that the program run successfully, while a non zero value means there was a problem. The explicit use of a return(o) statement will indicate that the program was successfully executed 3.3. Function Prototype ‘The general form of a function is retum-type function-name (parameter list) © Return-type: specifies the type of data that the function retums. © Parameter-list comma-separated list of variables names and their associated types that receive the values of the arguments when the function Is called. The general form of a parameter daciaration list is f (type var 1, type 2, - ox example £ £ (int a, 3.4 The Function Declaration ‘The most common approach is to declare the function at the baginning of the program Inthe example program the function asterisk() is declared in the line, void asterisk() The declaration tells the compiler that at some later point we plan to present a function called asterisk’ The keyword void specifies thet the function has no retumn valuo, and the emply parentheses indicate that it takes no arguments, 3.5 Calling the Function ‘The function is called three times from main(). Each of the three calls looks like this: asterisk() This is all we need to call the function: the function name, followed by parentheses. The syntax of the call is very similar to that of the declaration, except that 61 Notes 62 Notes ‘Object Oriented Programming wit C+ the retumtype is not used. The call is terminated by @ semicolon. Executing the call statement causes the function to execute, that is, control is transferred to the function, ‘the statements in the function definition are executed, and then cantrol returns to the statement following the function call 3.6.1 The Function Definition ‘The definition contains the actual code for the function. The definition for asteriski) is: declarator The definition consists of a line called the declarator, followed by the function body. The function body is composed of the statements that make up the function, delimited by braces. The declarator must agree with the declaration 1¢. it must use the same function name, the seme argument types in the same order and the same return type Notice that the declarator is not terminated by a semicolon When the function is called, control is transferred to the first statement in the function body. The other statements in the function body are then executed, and when the closing brace is encountered, control retums to the calling program 3.6.2 Eliminating the Declaration You can eliminate the function declaration if the function definition appears in the listing before the first call to the function. For example, we could rewrite our first example program as follows: // eliminating fun # include at <<"Name cute" tcc" Nehax" using namespace std; void swapiint &x, int By); intmain 0) C local variable declaration: 10 20, cout <« "Before swap, value of a " << a << endl cout << "Before swap, value of b” << b << endl swapia, b) cout << "Afler swap, value of a" < sing namespace std, double vals] = (10.1, 126, 33.1, 24.1, 50.0); double& setValues( int |) { return vals; //it will retum a reference to the ith element } intmain 0) { cout << "Value before change” << endl for (inti= £ cout <<"vals[" << <<" yi 5+) cout << valsfl] << endl } setValues(1 sefValues(3) = 708 cout <« "Value after change" <« endl Functions for (inti= 0, 1<5; 14+) ‘ cout << "vals" << i <<") cout << vaisfi] << endl t return 0 } Output Value before change vals[2] = 33.1 vals[3] = 70.6 valsfa] = 50 3.8 Inline Functions One of the objectives of using functions in a program is to save memory space, which becomes appreciable when a function is ikely to be called many times. But, 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 functions, saving registers, pushing arguments into the stack and returning to the calling function. All these instructions slaw down the program, (C++ has a solution to solve this problem. To eliminate the costs of calls to small functions, C++ proposes a new feature called Inline functions. As inline function is @ function that is expanded in line whan it fs invoked. That is, the compiler replaces the function call with the corresponding function code. Functions that are very short, say ‘one or two statemants, are candidates to be inlined. The inline functions are defined as follows line function - header 7 function body Here's a variation of conversion program that converts weight in pounds to kilograms: Jf demonstrates ine fonetions 65 Notes 86 Notes (Object Oriented Programmimg with C+ # include pdtokg() - defini Line float on of functio! ‘okg (float pound: in pounds:"; itoke (pds) : To make a function inline, the keyword inline is needed in the function definition inline float pdtokg (float pounds) In INLINE, we must place the definition of function hefore main(). This is because the compiler must insert the actual code into the program, not just instructions to call the function, Be aware that the inline keyword is actually just a request to the compiler Somelimes the compiler will ignore the request and compile the function as @ normal function 3.9 Default Arguments (C++ aiso allows us to call a function without specifying all its arguments. In such cases, the function assigns @ default value to the parameter which does not fave a matching argument in the function call. Defaull values are specified when the function is declared The compiler looks at the prototype to see how many arguments @ function uses and alerts the program for possible default values. Here's an example. J/ demonstrates missing an default arguments repehar (); // prints 40 repchar ("+"): repehar (" = ax () void repchar (char ch, int n) in; it) out <

You might also like