|
Just as any variable is declared in a
program before it is used, it is necessary to declare or
prototype a function to inform the compiler that the
function would be referenced at a later point in the
program.
In Program 7.1, the statement:
void add();
is a function declaratoin or a prototype.
Defining a Function
The function definition contains the code for the function.
The function definition for add() in Program 7.1 is:
//Function definition for add
void add()
{
int iNum1, iNum2, iNum3;
cin>>iNum1;
cin>>iNum2;
iNum3 = iNum1 + iNum2;
cout<<"The sum of the two numbers is"<<iNum3<<endl;
}
A function declaration can be avoided if the function
definition appears before the first call to the function.
Program 7.1 can be modified to avoid function declaration in
the following way:
//Program 7.2
//This program uses a function to calculate the sum of two
numbers
#include<iostream.h>
void add()
{
int iNum1, iNum2, iNum3;
cin>>iNum1;
cin>>iNum2;
iNum3 = iNum1 + iNum2;
cout<<"The sum of the two numbers is"<<iNum3<<endl;
}
void main()
{
cout<<"Calling function add()"<<endl;
add(); //A call to the function add(), while calling a
function the command is terminated with a ';'
cout<<"A return from add() function"<<endl;
}
Function Arguments
Argument(s) of a function is(are) the data the function
receives when called from another function. It is not always
necessary for a function to have arguments. The function
add() in Program 7.1 did not contain any arguments. The
add() function in Program 7.1 can be modified to accept two
arguments in the following way:
//Program 7.2
#include<iostream.h>
vodi main(int iVar1, int iVar2) //Function containing two
arguments
{
int iVar3 = iVar1 + iVar2;
cout<<"The sum of the two numbers is: "<<iVar3<<endl;
}
void main()
{
int iNum1, iNum2;
cout<<"Input tow numbers "<<endl;
cin>>iNum1;
cin>>iNum2;
add(iNum1, iNum2); //Passing two values to the function
add()
} |