Professional Documents
Culture Documents
More On Functions:: Objectives
More On Functions:: Objectives
1
Body of payrollFNS.cpp Functions and Procedures
Note that in computer science in general
“function” means a sub-task that returns a single
value
reflecting the mathematical meaning of function
“procedure” is the term used for sub-tasks that
do something rather than returning something.
C++ used the word function for all sub-tasks.
2
WRONG definition of
Call-by-value parameters
read_details ()
void read_details (int Up to now, our parameters are call-by-value
num_hours, double hourly_rate, The value of the argument is passed in.
double tax_credit) { Read_details (num_hours, … ) will pass in 0 or
… whatever num_hours happens to be at that time.
cin >> num_hours; The parameter variable num_hours inside
… read_details function is initialised to 0, and then cin
gives it another value.
}
But the main num_hours variable is not affected.
This won’t change the value of the main See lecture for details.
program’s variable num_hours.
3
Which to use Clean living!!
If you want a function to change the value of a Functions that return a value should have
variable it must be a call-by-reference parameter no other effect
i.e. use & Including they should not update reference
If the function only needs the value of the parameters.
parameter don’t use & If your function needs to return multiple
it’s confusing - the reader will expect the function to values use reference parameters for all of
change the value them and make it a void function.
and dangerous - the function may inadvertently
change the value of a main program variable.
This is recommended practice, not
absolute.
Exercises
We can now complete the “functions”
version of the payroll program.
Write a function to swap the values of two
integer variables.
Write a function to order the values of two
integer variables, so that x <= y.
10 More on Functions 15