Presentation is loading. Please wait.

Presentation is loading. Please wait.

FUNCTIONS& FUNCTIONS OVERLOADING

Similar presentations


Presentation on theme: "FUNCTIONS& FUNCTIONS OVERLOADING"— Presentation transcript:

1 FUNCTIONS& FUNCTIONS OVERLOADING

2 Functions Basics A function groups a number of program statements into a unit and gives it a name. It is invoked from other parts of the program.

3 Functions The most important reason to use functions is to aid in the conceptual organization of a program. Another reason to use functions is to reduce program size. Any sequence of instructions that appears in a program more than once is a candidate for being made into a function. The function’s code is stored in only one place in memory, even though the function is executed many times in the course of the program.

4

5 SIMPLE FUNCTIONS In C++ program main () function is used for calling a program. How can we add other functions to a program? There are three components of a functions: Function Declaration Function Calling Function Definition

6 SIMPLE FUNCTIONS Just as you can’t use a variable without first telling the compiler what it is, you also can’t use a function without telling the compiler about it. There are two ways to do this. declare the function before it is called. define it before it’s called

7 Function declarations are also called prototypes, since they provide a model or blueprint for the function. They tell the compiler, “a function that looks like this is coming up later in the program

8

9

10 Example using namespace std; void starline(); //function declaration // (prototype) int main() { starline(); //call to function cout << “Data type Range” << endl; starline(); //call to function cout << “char -128 to 127” << endl << “short -32,768 to 32,767” << endl << “int System dependent” << endl << “long -2,147,483,648 to 2,147,483,647” << endl; return 0; } // function definition void starline() //function declarator

11 for(int j=0; j<45; j++) //function body
cout << ‘*’; cout << endl; } output ********************************************* Data type Range char -128 to 127 short -32,768 to 32,767 int System dependent double -2,147,483,648 to 2,147,483,647

12 Comparison with Library Functions
For Example: ch = getche(); The declaration is in the header file specified at the beginning of the program. The definition (compiled into executable code) is in a library file that’s linked automatically to your program when you build it.

13 Eliminating the Declaration
The second approach to inserting a function into a program is to eliminate the function declaration and place the function definition (the function itself) in the listing before the first call to the function.

14 Eliminating the Declaration
using namespace std; //no function declaration // // starline() //function definition void starline() { for(int j=0; j&lt45; j++) cout << ‘*’; cout << endl; } int main() //main() follows function starline(); //call to function cout << “Data type Range” << endl; cout << “char -128 to 127” << endl << “short -32,768 to 32,767” << endl << “int System dependent” << endl << “long -2,147,483,648 to 2,147,483,647” << endl; return 0;

15 Passing Arguments to Functions
An argument is a piece of data (an int value, for example) passed from a program to the function. Arguments allow a function to operate with different values, or even to do different things, depending on the requirements of the program calling it.

16 Passing Arguments to Functions
Passing Constants Passing Variables -Passing by Value -Passing by Reference

17 Passing Constants Suppose instead of a function that always prints 45 asterisks, we want a function that will print any character any number of times.

18 Example #include <iostream> using namespace std; void repchar(char, int); //function declaration int main() { repchar(‘-’, 43); //call to function cout << “Data type Range” << endl; repchar(‘=’, 23); //call to function cout << “char -128 to 127” << endl << “short -32,768 to 32,767” << endl << “int System dependent” << endl << “double -2,147,483,648 to 2,147,483,647” << endl; repchar(‘-’, 43); //call to function return 0; }

19 Example // repchar() // function definition void repchar(char ch, int n) //function declarator { for(int j=0; j&ltn; j++) //function body cout << ch; cout << endl; }

20 Passing variables #include <iostream> using namespace std; void repchar(char, int); //function declaration int main() { char chin; int nin; cout << “Enter a character: ”; cin >> chin; cout << “Enter number of times to repeat it: ”; cin >> nin; repchar(chin, nin); return 0; } // // repchar() // function definition void repchar(char ch, int n) //function declarator

21 for(int j=0; j<=n; j++) //function body
cout << ch; cout << endl; }

22 Structures as Arguments
Entire structures can be passed as arguments to functions.

23 Passing a Distance Structure
#include &ltiostream> using namespace std; //////////////////////////////////////////////////////////////// struct Distance //English distance { int feet; float inches; }; void engldisp( Distance ); //declaration int main() Distance d1, d2; //define two lengths //get length d1 from user cout << “Enter feet: ”; cin >> d1.feet; cout << “Enter inches: ”; cin >> d1.inches; //get length d2 from user cout << “\nEnter feet: ”; cin >> d2.feet; cout << “Enter inches: ”; cin >> d2.inches;

24 Passing a Distance Structure
cout << “\nd1 = ”; engldisp(d1); //display length 1 cout << “\nd2 = ”; engldisp(d2); //display length 2 cout << endl; return 0; } // // engldisp() // display structure of type Distance in feet and inches void engldisp( Distance dd ) //parameter dd of type Distance { cout << dd.feet << “\’-” << dd.inches << “\””;

25 Returning Values from Functions
#include &ltiostream> using namespace std; float lbstokg(float); //declaration int main() { float lbs, kgs; cout << “\nEnter your weight in pounds: ”; cin >> lbs; kgs = lbstokg(lbs); cout << “Your weight in kilograms is ” << kgs << endl; return 0; } // // lbstokg() // converts pounds to kilograms float lbstokg(float pounds) float kilograms = * pounds; return kilograms;

26 Returning Structure Variables
#include &ltiostream> using namespace std; //////////////////////////////////////////////////////////////// struct Distance //English distance { int feet; float inches; }; Distance addengl(Distance, Distance); //declarations void engldisp(Distance); int main() Distance d1, d2, d3; //define three lengths //get length d1 from user cout << “\nEnter feet: ”; cin >> d1.feet; cout << “Enter inches: ”; cin >> d1.inches;

27 //get length d2 from user
cout << “\nEnter feet: ”; cin >> d2.feet; cout << “Enter inches: ”; cin >> d2.inches; d3 = addengl(d1, d2); //d3 is sum of d1 and d2 cout << endl; engldisp(d1); cout << “ + ”; //display all lengths engldisp(d2); cout << “ = ”; engldisp(d3); cout << endl; return 0; } // // addengl() // adds two structures of type Distance, returns sum Distance addengl( Distance dd1, Distance dd2 ) { Distance dd3; //define a new structure for sum dd3.inches = dd1.inches + dd2.inches; //add the inches dd3.feet = 0; //(for possible carry) if(dd3.inches >= 12.0) //if inches >= 12.0, { //then decrease inches

28 dd3.inches -= 12.0; //by 12.0 and dd3.feet++; //increase feet } //by 1 dd3.feet += dd1.feet + dd2.feet; //add the feet return dd3; //return structure } // // engldisp() // display structure of type Distance in feet and inches void engldisp( Distance dd ) { cout << dd.feet << “\’-” << dd.inches << “\””;

29 Inline Functions To save execution time in short functions, you may elect to put the code in the function body directly in line with the code in the calling program. That is, each time there’s a function call in the source file, the actual code from the function is inserted, instead of a jump to the function. All you need is the keyword inline in the function

30 Inline functions

31 Example using namespace std; // lbstokg() // converts pounds to kilograms inline float lbstokg(float pounds) { return * pounds; } // int main() float lbs; cout << “\nEnter your weight in pounds: ”; cin >> lbs; cout << “Your weight in kilograms is ” << lbstokg(lbs) << endl; return 0;

32 Variables and Storage Classes
The storage class of a variable determines which parts of the program can access it and how long it stays in existence. Three storage classes automatic external static

33 Automatic Variables Variables defined within a function body are called automatic variables. Variables defined within a function are automatic anyway Auto, can be used to specify an automatic variable. void somefunc() { auto int somevar; //same as int somevar auto float othervar; //same as float othervar // other statements }

34 Life time An automatic variable is not created until the function in which it is defined is called. The time period between the creation and destruction of a variable is called its lifetime. The idea behind limiting the lifetime of variables is to save memory space. If a function is not executing, the variables it uses during execution are presumably not needed

35 Visibility/Scope A variable’s visibility describes the locations within a program from which it can be accessed Automatic variables are only visible, meaning they can only be accessed, within the function in which they are defined. Automatic variables are sometimes called local variables, since they are visible only locally, in the function where they are defined.

36 Initialization When an automatic variable is created, the compiler does not try to initialize it. Thus it will start off with arbitrary value, which may be 0 but probably will be something else. If you want it initialize, you must do it explicitly, as in int n = 33;

37 External Variables External variables are defined outside of (external to) any function. An external variable is visible to all the functions in a program. More precisely, it is visible to all those functions that follow the variable’s definition in the listing. These are declared in the begin of the listing(program) External variables are also called global variables

38 Example #include <iostream> using namespace std; char ch = ‘a’; //external variable ch void getachar(); //function declarations void putachar(); int main() { while( ch != ‘\r’ ) //main() accesses ch getachar(); putachar(); } cout << endl; return 0;

39 Initialization IF an external variable is initialized explicitly then after first loading initialized value is assigned to a variable unless it is changed by other part of the program. If an external variable is not initialized explicitly the compiler automatically assigns ‘0’ value to a variable.

40 Life time and Visibility
External variables exist for the life of the program. That is, memory space is set aside for them when the program begins, and continues in existence until the program ends.

41 Static Variables Static variables are initialized only once in a program. Static variables retain their values and available for next call.

42 Example #include <iostream> using namespace std;
float getavg(float); //declaration int main() { float data=1, avg; while( data != 0 ) cout << “Enter a number: ”; cin >> data; avg = getavg(data); cout << “New average is ” << avg << endl; } return 0; //

43 // getavg() // finds average of old plus new data float getavg(float newdata) { static float total = 0; //static variables are initialized static int count = 0; // only once per program count++; //increment count total += newdata; //add new data to total return total / count; //return the new average }

44 Difference between static variable and normal local variable
A static variable in a function body e.g in previous example count ( static variable) works like shared data and retain values till next call. A normal local variable does not share data and loses values for every call. For example if a user initializes value to ‘0’ for normal local variable then for next function call it will be ‘0’ again for count++. But in case of static variable the count++ value will be retained and will be incremented for every call.

45 Storage Automatic variables are stored on the stack, while external and static variables are stored on the heap.

46 Constant member functions
A const member function guarantees that it will never modify any of its class’s member data. class aClass { private: int alpha; public: void nonFunc() //non–const member function { alpha = 99; } //OK void conFunc() const //const member function { alpha = 99; } //ERROR: can’t modify a member };


Download ppt "FUNCTIONS& FUNCTIONS OVERLOADING"

Similar presentations


Ads by Google