Monday, August 12, 2013

What are functions and why do we use them? What is meant by function overloading?

Function is a chunk of statements called from some other part of a program. It is easy to organize program through functions. It can reduce programming mistakes and code repetition. Additionally, it can enhance code readability and we can trace errors easily. There are three things to keep in mind for writing a function in our program:

1. Function prototype
2. Fnction call
3. Function definition

Function prototype should be before function call so that compiler can have knowledge of function before calling instruction (otherwise it will raise error). Function definition syntax is as follows:

 return-type function-name( datatype parameter1, datatype parameter2, ...)
 { statements }

Where: return-type is the data type of the data returned by the function. Function-name is name of function. parameters (you can specify any number of parameters) statements are the commands. It is a block of statements surrounded by braces { }.

 Lets write a sample code of adding two numbers with the help of function.

#include void add (int int); //function declaration 
void main() 

int x,y; 
cout<<"enter two numbers for addition"; 
cin>>x>>y; 
add(x,y); ///function call


void add(int a,int b) //function definition
{
int c;
c=a+b;
cout<"addition of two numbers is"<<c;
}

This is a simple code. You can do many other complex examples also for understanding functions.
now functions can be of different types. these are function pass by value, function pass by reference, inline function and function overloading.

Function overloading, (as the name is reflecting overloading means more than one) is concept where we can write more than one function having same name in one program. such as i can write one more add() function in above program. But there are certain rules for it. you must fulfill at least any one of following condition.

1. No of function arguments should be different OR
2. Type of at least one argument should be different OR
3. Return type of functions should be different.

Here is modified version of above add() function. Now i want to add not only two int numbers but i also want to do the same task but with float and double numbers. Here is the code:

#include<iostream.h>
void add (int,int); //first function declaration
void add (double,float); // second function declaration
void main()
{
int x,y;
double d;
float f;
cout<<"enter two numbers for addition";
cin>>x>>y;
cout<<"enter more two numbers for addition";
cin>>d>>f;
add(x,y); ///function call
add(d,f); /second function call
}
void add(int a,int b) //function definition
{
int c;
c=a+b;
cout<"addition of two numbers is"<<c;
}

void add(double a,float b) //function definition
{
double c;
c=a+b;
cout<"addition of two numbers is"<<c;
}

I hope it will have clear now the concept of basic function and function overloading.

No comments:

Post a Comment