Presentation is loading. Please wait.

Presentation is loading. Please wait.

Functions Chapter No. 5.

Similar presentations


Presentation on theme: "Functions Chapter No. 5."— Presentation transcript:

1 Functions Chapter No. 5

2 Contents Simple functions Passing arguments to functions
Reference arguments Default arguments const Function arguments Returning values from functions Overloaded functions Inline functions Recursion Scope and storage classes Returning by reference

3 Simple functions A function groups a number of program statements into a unit and gives it a name Conceptual organization of a program Reduce the program size A function is made when same work in a program is repeated for more than one time Function’s code is stored in only one place in memory

4 Function Components Component Purpose Example Declaration
Specifies function name, argument type and return value. Alerts compiler (or programmer) that a function is coming up later Void func(); Call Causes the function to be executed Func() Definition The function itself. Contains the lines of code that constitute the function Void func() { //lines of code } Declarator First line of definition

5 Example #include<iostream.h> void starline (); Int main() { starline(); cout<<“Data type Range”<<endl; cout<<“char -128 to 127”<<endl; cout<<“short -32,768 to 32,767”<<endl; cout<<“int -2,147,483,648 to 2,147,483,6487”<<endl; return 0; } // void starline() for(int i=0; i<45; i++) cout<<‘*’; cout<<endl;

6 Passing arguments to function
An argument is a piece of data, e.g. int value, passed from a program to the function Passing constants starline(char , int); //function declaration: must mention type of arguments to be passed later starline(‘=’, 45) //call to function ‘=’ and 45 passed as constant arguments starline(char ch, int n) // function declarator (variables hold the argument values are called parameters) { // function body for(int i=0; i<n;i++) cout<<ch; cout<<endl; }

7 Passing variables- by value
void repchar(char, int); int main() { Char chin; Int nin; Cout<<“Enter a character: ”; cin>> chin; Cout<<“Enter number to time to repeat it: ”; cin>>nin; repchar(chin, nin); return 0; } // void repchar(char ch, int n) for(int i= 0; i<n; i++) cout<<ch; repchar(chin, nin); in main() causes the values in these variables to be copied into parameters in repchar(ch, n)

8 Structure as arguments
Struct Distance{ int feet; float inches}; // structure declaration Void engldisp(Distance); // function declaration // Int main() { Distance d1; Cout<<“Enter feet”; cin>>d1.feet; Cout<<“Enter inches”; cin>>d1.inches; engldisp(d1); // function call return 0; } // Void engldisp(Distance dd) cout<<dd.feet<<“------”<<dd.inches;

9 Reference arguments A reference is an alias – different name – for a variable Instead a value is being passed to the function, a reference (memory address) to the original variable, in the calling program, is passed Reference arguments are indicated by the ampersand (&) sign following the data type e.g. float& intp The & indicates that intp is an alias – another name – for whatever variable is passed as an argument

10 Cont’d main() { int i = 10, j = 20; swapThemByVal(i, j); cout << i << " " << j << endl; // displays swapThemByRef(i, j); cout << i << " " << j << endl; // displays } void swapThemByVal(int num1, int num2) { int temp = num1; num1 = num2; num2 = temp; } void swapThemByRef(int& num1, int& num2)

11 Difference between pass by value and pass by reference
swapThemByVal() at start swapThemByVal() after assignment Main() temp …. num1 10 num2 20 temp 10 num1 20 num2 i 10 j 20 temp …. num1 --- num2 swapThemByRef() i 10 j 20 temp 10 num1 --- num2 swapThemByRef(): After assignment i 20 j 10 Difference between pass by value and pass by reference

12 Default arguments A function can be called without specifying all its arguments It can be done when declaration must provide default values for those arguments Default arguments are useful when arguments have always same values Example Void repchar( char =‘*’, int = 45)// declaration with default args. ///////---call in main()---- Repchar(); Repchar(‘=’); Repchar(‘+’,30);

13 const Function Arguments
Passing arguments by reference can modify a variable in calling program When you want to pass an argument by reference but not want to modify a variable, const modifier is used for this purpose A variable already defined as const in the calling program must be passed as const argument

14 Example Void aFunction(int&, const int& b); Int main() { Int alpha = 7; Int beta = 11; aFunction(alpha, beta); return 0; } Void aFunction(int& a, const int& b) a = 107; //OK b = 111; //error: can’t modify constant argument

15 Returning values from functions
When a function completes its execution it can return a single value to the calling program A return is actually a answer to the problem that function has solved When a function returns a value the data type must be specified Data type is mentioned in function declaration part return statement is use to return value Multiple values can be returned using reference arguments and other is return a structure

16 Example int add(int a,int b); int main() { int num1,num2,result; cout << " Enter number1: " << num1<< endl; cin>>num1; cout<<“Enter number 2: ”<<endl; cin>>num2; result = add(num1,num2); cout << " The result is : " << result << endl; return 0; } int add(int a, int b) int add; add = a + b; return add; }

17 Overloaded Functions In C++ two different functions can have the same name if their parameter types or number are different Compiler decides which function to call, depends on number of parameters or types int operate (int a, int b) { return (a*b); } float operate (float a, float b) { return (a/b); } int main () { int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); return 0; } Output 10 2.5

18 Inline functions Single copy of function is placed in memory
Multiple calls are made from main program causes multiple jumps in memory which takes extra time for execution Inline function suggests compiler to place function code at each point the function is called The format for its declaration is: inline type name ( arguments ... ) { instructions ... }

19 Recursion Recursion involves a function calling itself
long factorial (long a) { if (a > 1) return (a * factorial (a-1)); else return (1); } int main () long number; cout << "Please type a number: "; cin >> number; cout << “Factorial of ”<< number<<“is ”<< factorial (number); return 0;

20 Scope and Storage class
Scope of a variable determines which part of program can access it. Two kinds Variables with local scope are visible only within block Variables with file scope are visible throughout a file Storage class determines how long it stays in existence Automatic: exist during lifetime of the function in which they are defined static : exist for the lifetime of the program

21 Cont’d Local Static local global Visibility Function File Lifetime
Program program Initialized value Not initialized Storage Stack Heap Purpose Variables used by a single function Same as local, but retains value when function terminates Variables used by several functions

22 Returning by Reference
Function that returns a reference is treated as if it were a variable. It returns alias to a variable There are two corollaries to this Can’t return a constant in setx() Can’t return a reference to local variable int x; int& setx() { return x; } int main() setx()=98; cout << "X: " << x<< endl; return 0;


Download ppt "Functions Chapter No. 5."

Similar presentations


Ads by Google