User Menu

Login



Share with

User Defined Functions PDF Print E-mail

Introduction to User-defined functions

C++ allows programmers to define their own functions. For example the following is a definition of a function which return the sum of two numbers.

int SumOfNumbers(int a,int b)

// Returns the sum of a and b

   { 

   int c;  //local variable

    c = a+b;

    return c;

   }

This function has two input parameters, a , b and will returns the sum of these parameters. In the function a local variable c is used to temporarily hold the calculated value inside the function.
The general syntax of a function definition:

    Return-type function-name( Data_Type parameter )

    {

      Statements;

    }

If the function returns a value then the type of that value must be specified in return-type. This could be int, float or char or any other valid data type. If the function does not return a value then the return-type must be void.

  1. 1.The function-name follows the same rules of composition as identifiers.
  2. 2.The parameter-list the formal parameters offunction along with their data types.
  3. 3.The statements consist of any C++statements.

Types of user Defined Functions

 

  1. 1.Functions with no parameters
  2. 2.Functions with parameters and no return value
  3. 3.Functions that return values
  4. 4.Call-by-value
  5. 5.Call-by-reference

Functions with no parameters

Functions with no will not return a value but carry out some operation. For example consider the following function with no parameters.

void Display(void)

//void inside the parenthesis is optional

 {
    cout << "Your Message"<< endl;

 }

Note that the return has been given as void, this tells the compiler that this function does not return any value. Because the function does not take any parameters the parameter-list is empty, this is indicated by the void parameter-list.

Since this function does not return a value it cannot be used in an expression and is called by treating it as a statement as follows:

Display();

When a function is called the C++ compiler must insert appropriate instructions into the object code. To do this correctly the compiler must know the types of all parameters and the type of any return value. Thus before processing the call of a function it must be defined. This can be done by defining the functions outside the definition of main function:

#include <iostream.h>

void Display(void)  // Function Definition

  {

    cout <<"Hello World";

  }

void main()

{
  cout << "Inside main function";

  Display();  // call to Display Function
}
Function Prototype

A function prototype supplies information about the return type of a function and the types of its parameter. The function prototype is merely a copy of the function definition with body. Thus the function prototype for the function Display is:

void Display(void);

Example of Function Prototype:

#include <iostream.h>

void Display(void);  // function prototype

int main()

{
  cout << "Inside Main Function";

  Display();

  return 0;

}

void Display(void)    // Function definition

  {

    cout << endl <<"Inside Display Function";
  }

Functions with parameters and no return value

The function Display() is now changed to the function DisplayValues which has to parameters a and b:

void DisplayValues(int a,int b)

  {

         cout << endl<<" a = "<<a <<endl <<" b = "<<b;

  }

As before this function does not return a value hence it is declared as having type void. It now takes two parameters a and b. The parameter list consists of Data type and a name for these formal parameters. Inside the body of the function their values are displayed.

The function is called in the same manner as Display(), but values must be given for the parameters a and b as shown below.

int main()

{
  int a = 2, b=4;

  DisplayValues(a,b);

     DisplayValues(2,4); /* Values can be given directly  

                        with variables*/

  return 0; 

 }

Note : Make sure that actual parameters data type must match the formal parameters data type given in the definition of the function.


While defining the function prototype for a function with parameters it is not necessary to specify the parameters names, we can simply write the Data types of each parameter separated by comma. Thus a suitable function prototype for the parameterised version of DispalyValues would be:

void DisplayValues(int,int); // No need to give name for parameters

Example 
#include <iostream.h>

// Function prototypes Only Data type of parameters is specified

void DisplayValues(int,int);

int main()

 int a,b;

 cout<<"Inside Main- Enter Two Values"<<endl;

 cin>>a>>b;
 cout<<"Call to DisplayValues Function";

 DisplayValues(a,b);
 return 0;

void DisplayValues(int a,int b) // Function Definition
   
  {

         cout << endl<<" a = "<<a <<endl <<" b = "<<b;
  }

Functions that return values

One of the most useful forms of function is one that returns a value . In this case the return type given in the function prototype is that of the value to be returned.

int CalSum(int a ,int b) // Here return type is integer which will Returns the sum of two integers
  {
    int c;  //local variable
    c = a+b;
    return c; // return statement
  }
The function prototype for this function is:
int distance(int, int); // function prototype

Some points to note:

  1. 1.The function has been given the return type int because it is going to return a integer value.
  2. 2.The parameter-list has two parameters, namely, a and b of integer type.
  3. 3.Inside the definition of CalSum there is a return statement.

Because this function returns a value it includes a return statement which returns the value. Return value may be a constant, a variable or an expression. Return statement cab be written as

return (a+b);
Example of function that will return a value
#include <iostream.h>
//Function prototypes Only Data type of parameters is specified
int CalSum(int  ,int );int main()

 int a,b,SUM;

 cout<<"Inside Main- Enter Two Values"<<endl;
 cin>>a>>b;
 
 SUM=CalSum(a,b);

//Here the value return by CalSum will be assigned to SUM

cout<<endl<<"The Sum of a and b is = "<<SUM; 

return 0;

int CalSum(int a ,int b)

  {

    int c;  //local variable

    c = a+b;

    return c; // return statement

  } 

Output

Inside Main- Enter Two Values

2 3

The Sum of a and b is = 5

Default Arguments

C++ allows a function to assign default values to parameters. The default value is assigned when no argument corresponding to that parameter is specified in the call to that function. For Example :

int calSum(int a = 10, int b = 20)

{
return a+b;

}
In the above code segment, if the CalSum() function is invoked without arguments, then the default values of 10 and 20 are assigned to a and b respectively. If values are passed to the function, then corresponding values are assigned to a and b.

Example of Default Arguments 

//This program illustrates the use of default arguments

#include<iostream.h>
void CalSum(int a = 10, int b = 20)

{
cout<<"Sum is "<<a+b<<endl;

}
void main()

{
int a = 2, b = 4;

CalSum(); // Without Arguments Call will use Default Arguments

CalSum(a,b); // With Arguments Call will not use Default Arguments

}
Output:
Sum is 30

Sum is 6

Use of One default arguments

//This program illustrates the use of ONE default arguments

#include<iostream.h>
void CalSum(int a , int b = 20)

{
cout<<"Sum is "<<a+b<<endl;

}
void main()

{
int a = 2, b = 4;

CalSum(a); // With one Argument Call will use ONE Default Argument

CalSum(a,b); // With Arguments Call will not use Default Arguments

}
Output:
Sum is 22

Sum is 6

Some points to remember when using default arguments:

Default arguments must be the last argument(s)(Right to Left). Therefore, the following code is illegal:

    int CalSum(int a=20 ,int b,int c); // Wrong

    int CalSum(int a ,int b=20 , int c); // Wrong

    int CalSum(int a =10 ,int b=20 , int c); // Wrong

Right method to specify Default Arguments is

 int CalSum(int a ,int b=10 , int c=20); // Right

 int CalSum(int a =5 ,int b=10 , int c=20); // Right 

Call by value and Call by Reference

When C++ passes arguments to functions it passes them by value. There are many cases when we may want to alter a passed argument in the function and receive the new value back to the calling function. C++ uses pointers explicitly to do this. The best way to study this is to look at an example where we must be able to receive changed parameters. Let us try and write a function to swap variables:

// Call by Value Example
#include<iostream.h>
int main()

  {
   void swap(int m,int m);
   int a=10 ,b=20;
   swap(a,b); // Call by value
      
cout<<"After interchanging the values ";  

   cout<<" a = "<<a<<endl<<"b = "<<b;
   return 0;
 }
void swap(int m ,int n)

 {
  int a;
  a=m;
  m=n;
  n=a;
  cout<<"Inside swap function the values are ";
  cout<<endl<<" m = "<<m<<endl<<" n= "<<n;
 }
 output:
 Inside swap function the values are
 m=20
 n=10;
 After interchanging the values
 a=10
 b=20

Note: No change to the values of a and b inside the calling function .Because when we pass values to the function only the copies of those values get passed not the original data value .Any change made inside the called function to these data value is not reflected to the calling function. That is why we call it call by value.
swap(a, b)   WON'T WORK.

Pointers provide the solution: Pass the address of the variables to the functions and access address of function.

Thus our function call in our program would look like this:

swap(&a, &b)

// Call by Reference Example

#include<iostream.h>
int main()

  {

   void swap(int *m,int *m);

   int a=10 ,b=20;

   swap(&a,&b); // Call by reference

   cout<<"After interchanding the values ";

   cout<<" a = "<<a<<endl<<"b = "<<b;

   return 0;

 }
void swap(int *m ,int *n)

 {
  int a;

  a=*m;

  *m=*n;

  *n=a;

  cout<<"Inside swap function the values are ";

  cout<<endl<<" *m = "<<m<<endl<<" *n= "<<n;

 }
output:
Inside swap function the values are

*m=20
*n=10;
After interchanging the values

a=20
b=10   

Note: The values of a and b changed .Because when we pass reference of the values to the function  orginal data value are passed .Any change made inside the called function to these data value is reflected to the calling function. That is why we call it call by Reference.

scroll back to top