CPE221 PointersFunctions
CPE221 PointersFunctions
&
FUNCTIONS
Dr. Hisham Muhammad
Department of Electrical and Electronics Engineering
University of Lagos.
Pointers and Functions
Call by Reference: Variable’s Address to a Function (1)
If a called function must return several data items to a calling function, the
programmer can use the call by reference technique.
The calling function passes the addresses of its variables to the called
function, which then writes the data directly into the calling function’s
variables.
In the Calculate Cylinder Volume program, (5-9), we want to use a
GetCylinderDimensions function to ask the user to enter the radius and
height
To return two pieces of data to main, we shall use a call by reference. Figure
(a) – (d) illustrates
Call by Reference: Variable’s Address to a Function (3)
Program 5-9 Calculate Cylinder Volume 2nd Version
// Call by Reference using pointers to functions.
void GetCylinderDimensions(float *r_ptr, float *h_ptr)
#include <iostream> //pointers
const double pi = 3.14159265; {
float R, H;
void GetCylinderDimensions ( float*, float*);
cout << “\n Enter radius and hieight “;
//Prototypes pointers here
cin >> R >> H;
float CalcCylinderVolume ( float, float);
*r_ptr = R;
// Call by value here
*h_ptr = H;
int main() }
{
float radius, height, volume; float CalcCylinderVolume(float rad, float hgt)
GetCylinderDimensions(&radius, &height); {
//send addresses return (pi * rad * rad * hgt);
volume = CalcCylinderVolume(radius,height); //shortcut by doing calcs in return ()
//send values
}
cout << "\n Cylinder Volume = " << volume << endl;
}
Call by Reference: Variable’s Address to a Function (1)
main’s variables
int main()
volume height radius
{
float radius, height, volume;
GetCylinderDimensions(&radius, &height); Addresses: xFF10 xFF14 xFF18
//rest of main
}
xFF14
xFF18
Step 1: The addresses of the radius and the height are passed to the function and
stored in the pointer variables (a) Step 1
Call by Reference: Variable’s Address to a Function (2)
main’s variables
int main() height
volume radius
{
float radius, height, volume;
GetCylinderDimensions(&radius, &height); Addresses: xFF10 xFF14 xFF18
//rest of main
Step 2: The values of the radius and the height are obtained and stored in local variables
(b) Step 2
Call by Reference: Variable’s Address to a Function (3)
main’s variables
int main() volume height radius
{
float radius, height, volume; 10.00000
//rest of main
Step 3: The value in R is assigned where r_ptr is pointing. The radius value of
10.00000 is written into main’s radius variable (c) Step 3
Call by Reference: Variable’s Address to a Function (4)
main’s variables
int main() volume height radius
{
float radius, height, volume; 15.00000 10.00000
//rest of main
Step 4: The value in H is assigned where h_ptr is pointing. The height value of
15.00000 is written into main’s height variable (d) Step 4