/* Pointer Rewrite - The following function uses reference variables as
parameters.
int doSomething(int &x, int &y)
{
int temp = x;
x = y * 10;
y = temp * 10;
return x + y;
}
This program demonstrates the function using pointers instead of
reference variables. */
#include "Utility.h"
/* Function prototypes */
void getNumbers(int *, int *);
int doSomething(int *, int *);
int main()
{
int varX = 0,
varY = 0,
result = 0;
/* Pointer variables pointing to integers */
int *x = nullptr;
int *y = nullptr;
/* Pointers x and y are storing the
addresses of varX and varY */
x = &varX;
y = &varY;
cout << "\n\t\t\tDo Something - Function Demonstration\n";
cout << "\n\n\tIn Main Function:\n\n"
<< "\tThe initial value of variable varX is " << *x
<< " and its address in memory is " << x;
cout << "\n\tThe initial value of variable varY is " << *y
<< " and its address in memory is " << y << "\n\n";
/* Asks the user for two integer values */
getNumbers(x, y);
cout << "\n\n\tBack In Main Function:\n\n"
<< "\tThe new value of variable varX is " << *x
<< " and its address in memory is " << x;
cout << "\n\tThe new value of variable varY is " << *y
<< " and its address in memory is " << y << "\n\n";
cout << "\n\tNow performing some calculations using your "
<< "numbers in doSomething() ...\n\n";
/* Performs some calculations on the variables pointed to
by *x and *y */
result = doSomething(x, y);
cout << "\n\tBack In Main Function:\n\n";
cout << "\tThe new value of variable varX is " << *x
<< " and its address in memory is " << x;
cout << "\n\tThe new value of variable varY is " << *y
<< " and its address in memory is " << y << "\n\n";
cout << "\tThe result of the calculations performed "
<< "in doSomething() is: "
<< *x << " + " << *y << " = " << result << "\n\n";
pauseSystem();
return 0;
}
/* **********************************************************
Definition: getNumbers
This function accepts two pointers to integers as its
arguments. It gets two values for x and y from the user.
********************************************************** */
void getNumbers(int *x, int *y)
{
cout << "\n\tPlease enter two numbers:\n"
<< "\tx: ";
cin >> *x;
cout << "\ty: ";
cin >> *y;
}
/* **********************************************************
Definition: doSomething
This function accepts to pointers as its arguments. Three
calculations are performed:
* x gets the result of multiplying the value pointed to
by *y by 10
* y gets the result of multiplying the value pointed to
by *x assigned to temp by * 10
* x pointing to valX and y pointing to valY are added
and this result is returned.
This final calculation is performed directly in the return
statement.
********************************************************** */
int doSomething(int *x, int *y)
{
int temp = *x;
*x = *y * 10;
*y = temp * 10;
return (*x + *y);
}
Wednesday, March 15, 2017
Programming Challenge 9.5 - Pointer Rewrite
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment