You are on page 1of 73

Functions

Objectives
Using functions in C++ Explaining Library functions and User-defined functions Describing function types Parameter passing by value and by reference Inline functions contd on the next slide..
Programming in C++ Functions 1

Explaining Function Overloading Explaining Reference variables Explaining visibility of variables in functions Explaining Pointer to functions

Programming in C++ Functions

Introduction
A function groups together program statements into a named unit They introduce modularity into your program. A large program can be broken down into manageable pieces by using functions. Each function is an independent unit. It can be developed and maintained independently.

Programming in C++ Functions

To develop and use a function in your program you have to do three things. 1.Provide a function prototype. 2.Provide a function definition. 3.Call the function.

Programming in C++ Functions

Library Functions
When you are using a library function, you use the standard library header file to provide the prototype declaration. These functions have already been defined and compiled and the object code is available in the library files.

Programming in C++ Functions

Listing: A C++ program to illustrate the usage of library function in a program. #include <iostream.h> #include <string.h>

/* header file for the strlen() function*/

void main(void) { int len; char *string=Hello world, Hello beautiful world; len=strlen(string); cout<<The string is :<<string<<\n; cout<<Its length is :<<len<< characters\n;} The output of this program is in the next slide
Programming in C++ Functions 6

The last program prints the following output: The string is: Hello world, Hello beautiful world Its length is: 34 characters

Programming in C++ Functions

User Defined Functions


When you create your own functions, you have to handle all the three aspects yourself namely: 1.Providing a function prototype. 2.Providing a function definition. 3.Calling the function.

Programming in C++ Functions

Listing: A C++ program containing a user created function. #include <iostream.h> void simple_func(void); // function prototype void main(void) { cout<<You are in the main() function\n; simple_func(); //function call cout<<Back in the main() function\n; }

this program is contd on the next slide...

Programming in C++ Functions

void simple_func(void) //function definition begins here { cout<<You are in the simple_func() function\n; } The output of this program is in the next slide

Programming in C++ Functions

10

The above program prints the following output: You are in the main() function You are in the simple_func() function Back in the main() function

Programming in C++ Functions

11

In the last program, the statement void simple_func(void); is the function prototype.

In the function prototype declaration we specify, 1.The return type of the function. 2.The function name 3.The argument list.

Programming in C++ Functions

12

The general form of the function prototype declaration is as shown below: return_type function_name (argument list);

Programming in C++ Functions

13

Functions with arguments and no return value


Listing: A C++ program which passes a parameter to a function. #include <iostream.h> void hello_func(int); void main(void) { cout<<Calling hello_func() function\n; hello_func(3); } this program is contd on the next slide...
Programming in C++ Functions 14

void hello_func(int n) { for(int i=0;i<n;i++) cout<<Hello World\n; }

The output of this program is in the next slide

Programming in C++ Functions

15

The last program prints the following output: Calling hello_func( ) function Hello World Hello World Hello World

Programming in C++ Functions

16

Functions Returning Values


Listing: A C++ program with a function returning a value. #include <iostream.h> double volume_func(double); void main(void) { double side,volume; cout<<Enter a value for one side of a cube:; cin>>side; volume=volume_func(side); cout<<Volume of the cube with side <<side<< is <<volume<<\n;} contd on the next slide...
Programming in C++ Functions 17

double volume_func(double x) { double v; v=x*x*x; return(v); }


A sample run of the last program is shown below: Enter a value for one side of a cube : Volume of a cube with side 12.6 is : 12.6 2000.376

Programming in C++ Functions

18

Functions with return values require that you use return statements in your function definition segment. A function can have one or more return statements. A return statement without a value as shown below: return; will return void. A function can return only one value. But a function can have more than one argument.

Programming in C++ Functions

19

Passing an Array as Parameter to A Function


C++ allows derived data types, like arrays, structures etc; to be passed as function parameters.

Programming in C++ Functions

20

Listing: Passing an array as parameter to a function. #include <iostream.h> int sum_func(int *,int ); //function prototype void main(void) { int sum=0; int num[10]={1,2,3,4,5,6,7,8,9,10}; sum=sum_func(num,10); //function call cout<<Sum of integers from 1 to 10 is=<<sum<<\n; } contd on the next slide...
Programming in C++ Functions 21

int sum_func(int *p, int n) //function definition heading { int sum=0; for(int i=0;i<n;i++) sum=sum+p[i]; return(sum); } The output of this program is in the next slide

Programming in C++ Functions

22

The last program prints the following result: Sum of integers from 1 to 10 is = 55

In this example we are not passing the actual values as parameter. Instead we are passing the address of the location where the actual value is stored. This is called parameter passing by reference.

Programming in C++ Functions

23

Protecting the Array


Where an array is passed as a parameter to a function by reference, the statements in the function definition segment can alter the array elements. It may not be desirable all the time. Some protection mechanism has to be incorporated into the program to prevent this (using the const keyword).

Programming in C++ Functions

24

Listing: Using const keyword in function prototype and function definition heading. #include <iostream.h> int sum_func(const int *,int ); //function prototype void main(void) { int sum=0; int num[10]={1,2,3,4,5,6,7,8,9,10}; sum=sum_func(num,10); //function call cout<<"Sum of integers from 1 to 10 is="<<sum<<"\n";} contd on the next slide...

Programming in C++ Functions

25

int sum_func(const int *p, int n) //function definition heading { int sum=0; for(int i=0;i<n;i++) sum=sum+p[i]; // p[1]=100; return(sum); }

Programming in C++ Functions

26

Inline Functions
Inline functions speed up program execution at the cost of higher memory requirement. Normal function call involves many different operations like: The address of the instruction following the function call is saved in some memory locations. The content of the CPU registers are stored in some memory location.

Programming in C++ Functions

27

The parameters of the function call are copied into the temporary variables created in some memory locations. The CPU control is transferred to the starting address of the function segment. When the function segment is finished probably it may return some value to the calling function. This value is copied into some CPU registers or into some memory locations.

Programming in C++ Functions

28

When control is transferred back to the calling program, all the saved information is loaded back into the appropriate CPU registers. The calling program retrieves the returned value from the appropriate register or memory location and uses it in the rest of the program.

Programming in C++ Functions

29

But for an inline function The compiled code becomes inline with the code of the rest of the program. With inline code the program does not have to jump to other locations to execute the function. The disadvantage is this consumes large memory storage when an inline function has to be called several times in your program.

Programming in C++ Functions

30

To use inline functions in your program you have to do two things. Preface the function prototype declaration with the keyword inline. Place the function definition above all the functions that call it.

Programming in C++ Functions

31

Listing: A C++ program to illustrate inline functions. #include <iostream.h> inline double square(double n) { return n*n; }

contd on the next slide...

Programming in C++ Functions

32

void main(void) { double a=10.6; double b; cout<<Value of a=<<a<<\n; b=square(a++); cout<<Value of a*a=<<b<<\n; cout<<Final value of a=<<a<<\n; } The output of this program is in the next slide

Programming in C++ Functions

33

The above program prints the following output: Value of a=10.6 Value of a*a=112.36 Final value of a=11.6

Programming in C++ Functions

34

Macros and Inline Functions


Listing: A C++ program to illustrate the use of macro definition to square a number. #include <iostream.h> #define SQUARE(x) x*x void main(void) { double a=10.6; double b; cout<<Value of a=<<a<<\n; b=SQUARE(a++); cout<<Value of a*a=<<b<<\n; cout<<Final value of a=<<a<<\n;} contd on the next slide...
Programming in C++ Functions 35

The above program generates the following output: Value of a=10.6 Value of a*a=112.36 Final value of a=12.6

Inline functions do parameter passing, macros do text substitution.

Programming in C++ Functions

36

Function Overloading or Function Polymorphism


Function overloading or function polymorphism allows multiple functions to share the same name. Polymorphism means existing in different forms. The key to function overloading is the functions argument list. It is also called the function signature.

Programming in C++ Functions

37

Function overloading or function polymorphism allows us to define two or more functions with the same name but with different signatures.

This is explained with the help of the following program.

Programming in C++ Functions

38

Listing: A C++ program to illustrate function overloading or function polymorphism.

#include <iostream.h> unsigned long left_func(unsigned long,unsigned); char *left_func(char *,unsigned);

contd on the next slide...

Programming in C++ Functions

39

void main(void) { unsigned long num=12345; char *name=INDIA; unsigned n; for(n=1;n<=5;n++) cout<<left_func(num,n)<<\n; cout<<\n; for(n=1;n<=5;n++) cout<<left_func(name,n)<<\n;; }

contd on the next slide...


Programming in C++ Functions 40

unsigned long left_func(unsigned long num, unsigned n) { unsigned digits=1; if(digits > n) unsigned long nn=num; { if(n==0 || num==0) n=digits-n; return 0; while(n) while(nn/=10) num/=10; digits++; return num; } else continued return num; }

contd on the next slide...

Programming in C++ Functions

41

char *left_func(char *ptr,unsigned n) { if(n<0) n=0; char *p=new char[n+1]; for(int i=0;i<n&&ptr[i];i++) p[i]=ptr[i]; while(i<=n) p[i++]=\0'; return p; } The output of this program is in the next slide
Programming in C++ Functions 42

The last program prints the following output: 1 12 123 1234 12345 I IN IND INDI INDIA

Programming in C++ Functions

43

Functions with Default Arguments


A default argument is a value that is used automatically as the function argument when you omit the actual argument from a function call.

Programming in C++ Functions

44

You must add defaults from right to left. You cant provide default value for a particular argument, unless you provide default values for all the arguments to its right. void func(int m, int n, int j); // valid void func(int m, int n=2, int j=5); // valid void func(int m, int n=4, int j); // invalid

Programming in C++ Functions

45

Listing: A C++ program to show the usage of default function arguments. #include <iostream.h> char *left_func(char *ptr,int n=3); void main(void) { char *name=Hello World; cout<<left_func(name,5)<<\n; cout<<left_func(name)<<\n; } contd on the next slide...

Programming in C++ Functions

46

char *left_func(char *ptr,int n) { if(n<0) n=0; char *p=new char[n+1]; for(int i=0;i<n&&ptr[i];i++) p[i]=ptr[i]; while(i<=n) p[i++]=\0'; return p; } the output of this program is in the next slide...

Programming in C++ Functions

47

The above program will print the following output: Hello Hel

Programming in C++ Functions

48

Reference Variables
A reference variable is an alternate name or an alias for an already existing or already defined variable. The main use of reference variables is that they can be used as formal parameters in function definition. The advantage of using reference variables as formal parameters is the reduction in memory consumption.

Programming in C++ Functions

49

Creating A Reference Variable


To create a reference variable x_ref for an existing variable x, do the following: int x; int & x_ref =x; You can use x and x_ref interchangeably in your program.

Programming in C++ Functions

50

Listing: A C++ program illustrating the use of reference variables. #include <iostream.h> void main(void) { int x=100; int & x_ref=x; cout<<Value of x=<<x<<\n; cout<<Value of x_ref=<<x_ref<<\n; cout<<Address of x=<<&x<<\n; cout<<Address of x_ref=<<&x_ref<<\n; contd on the next slide...

Programming in C++ Functions

51

x++; cout<<Value of x after incrementing x =<<x<<\n; cout<<Value of x_ref after incrementing x =<<x_ref<<\n; x_ref++; cout<<Value of x after incrementing x_ref =<<x<<\n; cout<<Value of x_ref after incrementing x_ref =<<x_ref<<\n; } output of this program is in the next slide...

Programming in C++ Functions

52

The last program prints the following output: Value of x=100 Value of x_ref=100 Address of x=0x200afff4 Address of x_ref =0x200afff4 Value of x after incrementing x=101 Value of x_ref after incrementing x=101 Value of x after incrementing x_ref=102 Value of x_ref after incrementing x_ref=102

Programming in C++ Functions

53

Reference Variables as Function Parameters


Reference variables are used as formal parameters in function definition. This method of passing arguments to functions is called parameter passing by reference. Parameter passing by reference allows the called function to access variables in the calling function.

Programming in C++ Functions

54

Listing: A C++ program in which parameters are passed to a function by reference. #include<iostream.h> void swap_func(int &, int &); void main(void) { int a=100; int b=200; cout<<Before the function call:\n; cout<< Value of a =<<a<<\n; cout<< Value of b =<<b<<\n; cout<<\n; contd on the next slide...
Programming in C++ Functions 55

swap_func(a,b); cout<<After the function call:\n; cout<< Value of a =<<a<<\n; cout<< Value of b =<<b<<\n; } void swap_func(int & x,int & y) { int temp; temp=x; x=y; y=temp; } output of this program is in the next slide...
Programming in C++ Functions 56

The last program prints the following output: Before the function call: Value of a =100 Value of b =200 After the function call: Value of a =200 Value of b =100

Programming in C++ Functions

57

Functions Returning Reference


C++ allows us to return values by reference. Listing: A C++ program returning a reference. #include <iostream.h> int & func_name(int &); void main(void) { int x=10; int y=func_name(x); contd on the next slide...
Programming in C++ Functions 58

cout<<"Value of x :"<<x<<"\n"; cout<<"Value of y :"<<y<<"\n"; } int & func_name(int & z) { return(z); } This program prints the following output: Value of x : 10 Value of y : 10

Programming in C++ Functions

59

Pointers to Functions *
(The remaining topics in this chapter are optional) A function pointer is a variable that can hold the address of a function. When the operating system loads the .exe file of a program in the memory, each function of the program segment gets loaded at a certain memory location which is the address of that function. The name of the function gives the address of the function.

Programming in C++ Functions

60

Figure: Conceptual picture of an executable module loaded into the memory


Programming in C++ Functions 61

Listing: A C++ program to illustrate that the name of the function gives the address of the function. #include <iostream.h> int func_name(int); void main(void) { cout<<"address of the function func_name() is :"; cout<<(void *)func_name; } int func_name(int ii) { } output of this program is in the next slide...
Programming in C++ Functions 62

The last program printed the following output in one run. Address of the function func_name() is : 0x1b9002ad

Programming in C++ Functions

63

Declaring the Function Pointer


Consider the function with prototype declaration, int func_name(char, int); A pointer to this function is declared as follows: int (* func_name_ptr)(char, int); You can assign to the pointer the address of the function as: func_name_ptr = func_name;

Programming in C++ Functions

64

Listing: Overloaded functions and function pointers. #include <iostream.h> int func_name(char,int); int (*func_name_ptr1)(char,int); void main(void) { func_name_ptr1=func_name; cout<<"value of func_name_ptr1 :"<<(void *)func_name_ptr1<<"\n"; } int func_name(char ch,int ii) { } output is on the next slide....
Programming in C++ Functions 65

The last program generated the following output in one run. Value of func_name_ptr1 = 0x1b980310

The pointer variable func_name_ptr1 is assigned the address of the function whose return type and signature (i.e. argument list) matches with the return type and signature of the variable func_name_ptr1.

Programming in C++ Functions

66

Invoking the Function Using the Function Pointer


Consider the following declarations: int fun_name (char, int, double) - function prototype int (* func_name_ptr) (char, int, double) - function pointer The function can be invoked through the pointer likeint x = (* func_num_ptr) (a, 10, 15.6) invoking the function

Programming in C++ Functions

67

Listing: A C++ program in which a function is invoked using pointer. #include <iostream.h> void hello_func(int); void(*hello_func_ptr)(int); void main(void) { hello_func_ptr=hello_func; (*hello_func_ptr)(4); }

void hello_func(int n) { for(int i=0;i<n;i++) cout<<"Hello World\n"; }

output of this program is on the next slide...


Programming in C++ Functions 68

The last program prints the following output: Hello World Hello World Hello World Hello World

Programming in C++ Functions

69

Pointer to A Function as Parameter To A Function


Listing: A C++ program in which pointer to functions are passed as parameters to functions. #include <iostream.h> void hello_world(int); void hello_CMC(int); void (*hello_world_ptr)(int); void (*hello_CMC_ptr)(int); void func_name(int,void (*)(int)); contd on the next slide...
Programming in C++ Functions 70

void main(void) { hello_world_ptr=hello_world; hello_CMC_ptr=hello_CMC; func_name(4,hello_world_ptr); cout<<"\n"; func_name(2,hello_CMC_ptr); } void func_name(int n,void (*func_ptr)(int)) { (*func_ptr)(n); } contd on the next slide...
Programming in C++ Functions 71

void hello_world(int n) { for(int i=0;i<n;i++) cout<<"Hello World\n"; } void hello_CMC(int n) { for(int i=0;i<n;i++) cout<<"Hello CMC\n"; }

output of this program is on the next slide...

Programming in C++ Functions

72

__________________________________________________________________________

The last program prints the following output: Hello World Hello World Hello World Hello World Hello CMC Hello CMC

Programming in C++ Functions

73