Parameters are a useful way to get input into a function or output from a
function. Points to note:
- A function may have no parameters and return a single value by means
of a return statement. (This is output from the function.)
Example:
double Average()
{
int num1, num2;
cout<<"Enter 2 numbers to average: ";
cin>>num1>>num2;
return (num1+num2)/2.0;
}
void main()
{
cout<<Average();
}
- A function may have one or more value parameters that allow you to
send input into the function.
Example:
void Average(double num1,double num2)//num1 and num2 are formal parameters
{
cout<<(num1+num2)/2.0;
}
void main()
{
Average(50.0,100.0);//50.0 and 100.0 are arguments or actual
//parameters
}
- A function may have one or more reference parameters that allow you
to both send input to the function and get output from the function.
Example:
void Average(double num1,double num2,double & result)//result is passed by
//reference
{
result=(num1+num2)/2.0;
}
void main()
{
double n1=50.0, n2=100.0, answer=0.0;
Average(n1,n2,answer);
cout<<answer;
}
- You may have a combination of value and reference parameters.
- You may use a return statement in a function that uses parameters.
- A parameter should always be made a value parameter if it
is only used to send a value as input to the function. Use reference
parameters only when sending values as output. (There are some exceptions
to this rule. Arrays (which we will study soon) are passed by reference
even though the & is not used. Other data types will need to be passed
by reference. We will study those later on.)