A function, sometimes also referred to as a procedure or a sub-routine, is a group of statements which carry out a task. Functions are an important concept in programming. In fact, Procedural Paradigm relies on nothing but functions. They are defined so that we do not have to repeat the same statements again and again.
A very important function that we have all seen is the 'main()' function. In fact, the '()' is what chracterizes 'main' as a function. We have also seen the use of 'clrscr()' and 'getch()'. Now, though we may call these functions, they are defined elsewhere, that is, in 'conio.h'.
Similarly, we shall now see, how to make a function in C++. Suppose we have an application that displays a menu to the user after every event, then we can make menu as a function. Take a look at the code below :-
void menu()
{
clrscr();
cout<<"1. Add a record"<<endl;
cout<<"2. Delete a record"<<endl;
cout<<"3. Modify a record"<<endl;
cout<<"4. Exit"<<endl;
cout<<endl<<"Enter your choice : ";
}
void main()
{
menu();
.
.
.
menu();
}
Notice here that we made a function out of menu rather than writing the same output statements again and again. A point to notice here is that, before the function is called, we have defined it. What if, we want to define it after the main() but want to use it in the main() olny. Then we have to declare the function before we use it, and can then write its deinition anywhere. For example,
void menu();
void main()
{
menu();
.
.
.
menu();
}
void menu()
{
clrscr();
cout<<"1. Add a record"<<endl;
cout<<"2. Delete a record"<<endl;
cout<<"3. Modify a record"<<endl;
cout<<"4. Exit"<<endl;
cout<<endl<<"Enter your choice : ";
}
We now discuss two more important concepts in functions - arguments and return values. Arguments are parameters passed to the function for usage and return value is the value the function returns as an answer upon completion. Take a look at the program written below :-
#include <iostream.h>
int add(int a, int b)
{
int result;
result=a+b;
return (result);
}
int main ()
{
int r;
r = add(5,8);
cout<<"The result is "<<r;
return 0;
}
Notice here that 'a' and 'b' are passed the value 5 and 8 respectively, hence are the arguments. The value of 'result' calculated is 13 and serves as a return value to the main() function. This value is put into 'r' and then is printed out on the screen. Notice that both add() and main() are of 'int' type. This depends upon what data type is their return value. In this program, both the functions return integer type values.
References :-
http://www.cplusplus.com
http://www.developerfusion.com
Written by Rae
Member Of Knowledge Bank Tutorial Writers (#619)
This article was originally published by CyberArmy.net in the CyberArmy Library.
|
|